python(pymysql)之mysql簡單操作


一、mysql簡單介紹

  說到數據庫,我們大多想到的是關系型數據庫,比如mysql、oracle、sqlserver等等,這些數據庫軟件在windows上安裝都非常的方便,在Linux上如果要安裝數據庫,咱不得不首先推薦的是mysql數據庫了,而且Mysql數據庫的第一個版本就是發行在Linux系統上的。

MySQL是一個關系型數據庫管理系統,由瑞典MySQL AB公司開發,目前屬於Oracle公司。MySQL是一種關聯數據庫管理系統,關聯數據庫將數據保存在不同的表中,而不是將所有數據放在一個大倉庫內,這樣就增加了速度並提高了靈活性。MySQL的SQL語言是用於訪問數據庫的最常用標准化語言。MySQL軟件采用了雙授權政策(本詞條“授權政策”),它分為社區版和商業版,由於其體積小、速度快、總體擁有成本低,尤其是開放源碼這一特點,一般中小型網站的開發都選擇MySQL作為網站數據庫。由於其社區版的性能卓越,搭配PHP和Apache可組成良好的開發環境

二、安裝msql

  1、centos6.4編譯安裝mysql

  參考地址:http://www.centoscn.com/CentosServer/sql/2014/0316/2584.html

  2、windows安裝msyql  

官網下載地址:
http://dev.mysql.com/downloads/mysql/

三、mysql簡單操作

  可用過客戶端遠程操作mysql:Navicat for MySql工具

  1、啟動數據庫:

  

  鏈接數據庫:

  

  2、顯示數據庫

    

默認數據庫:
  mysql - 用戶權限相關數據
  test - 用於用戶測試數據
  information_schema - MySQL本身架構相關數據

   2、使用數據庫

    

  3、用戶授權

  用戶管理  

創建用戶
    create user '用戶名'@'IP地址' identified by '密碼';
刪除用戶
    drop user '用戶名'@'IP地址';
修改用戶
    rename user '用戶名'@'IP地址'; to '新用戶名'@'IP地址';;
修改密碼
    set password for '用戶名'@'IP地址' = Password('新密碼')
 
PS:用戶權限相關數據保存在mysql數據庫的user表中,所以也可以直接對其進行操作(不建議)

   授權管理:  

show grants for '用戶'@'IP地址'                  -- 查看權限
grant  權限 on 數據庫.表 to   '用戶'@'IP地址'      -- 授權
revoke 權限 on 數據庫.表 from '用戶'@'IP地址'      -- 取消權限   
all privileges 除grant外的所有權限 select 僅查權限 select,insert 查和插入權限 ... usage 無訪問權限 alter 使用alter table alter routine 使用alter procedure和drop procedure create 使用create table create routine 使用create procedure create temporary tables 使用create temporary tables create user 使用create user、drop user、rename user和revoke all privileges create view 使用create view delete 使用delete drop 使用drop table execute 使用call和存儲過程 file 使用select into outfile 和 load data infile grant option 使用grant 和 revoke index 使用index insert 使用insert lock tables 使用lock table process 使用show full processlist select 使用select show databases 使用show databases show view 使用show view update 使用update reload 使用flush shutdown 使用mysqladmin shutdown(關閉MySQL) super 􏱂􏰈使用change master、kill、logs、purge、master和set global。還允許mysqladmin􏵗􏵘􏲊􏲋調試登陸 replication client 服務器位置的訪問 replication slave 由復制從屬使用
權限
 對於目標數據庫以及內部其他: 數據庫名.* 數據庫中的所有 數據庫名.表 指定數據庫中的某張表 數據庫名.存儲過程 指定數據庫中的存儲過程 *.*                所有數據庫
數據庫
 用戶名@IP地址 用戶只能在改IP下才能訪問 用戶名@192.168.1.%   用戶只能在改IP段下才能訪問(通配符%表示任意) 用戶名@%             用戶可以再任意IP下訪問(默認IP地址為%)
對於用戶和IP

四、表操作

  1、在庫中創建表  

use test #選擇test庫
create table 表名(    #創建表
    列名  類型  是否可以為空,
    列名  類型  是否可以為空
)   
        是否可空,null表示空,非字符串
            not null    - 不可空
            null        - 可空 
        默認值,創建列時可以指定默認值,當插入數據時如果未主動設置,則自動添加默認值
            create table tb1(
                nid int not null defalut 2,
                num int not null
            ) 
        自增,如果為某列設置自增列,插入數據時無需設置此列,默認將自增(表中只能有一個自增列)
            create table tb1(
                nid int not null auto_increment primary key,
                num int null
            )
            或
            create table tb1(
                nid int not null auto_increment,
                num int null,
                index(nid)
            )
            注意:1、對於自增列,必須是索引(含主鍵)。
                 2、對於自增可以設置步長和起始值
                     show session variables like 'auto_inc%';
                     set session auto_increment_increment=2;
                     set session auto_increment_offset=10;

                     shwo global  variables like 'auto_inc%';
                     set global auto_increment_increment=2;
                     set global auto_increment_offset=10; 
        主鍵,一種特殊的唯一索引,不允許有空值,如果主鍵使用單個列,則它的值必須唯一,如果是多列,則其組合必須唯一。
            create table tb1(
                nid int not null auto_increment primary key,
                num int null
            )
            或
            create table tb1(
                nid int not null,
                num int not null,
                primary key(nid,num)
            ) 
        外鍵,一個特殊的索引,只能是指定內容
            creat table color(
                nid int not null primary key,
                name char(16) not null
            )

            create table fruit(
                nid int not null primary key,
                smt char(32) null ,
                color_id int not null,
                constraint fk_cc foreign key (color_id) references color(nid)
            )

   2、數據表操作:  

#基於Navicat for MySql工具實現操作
show tables; #查詢庫中有哪些表
create table lcj(
id int not null auto_increment PRIMARY KEY,  #PRIMARY KEY主鍵IP 自增
name char(30) not null, 
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default  "-");  #電話默認為-
SELECT * from lcj;  #查詢表
#插入數據
insert into lcj VALUES(0001,'xiaoluo','男',18,'13520617734')
#同時插入多條數據
insert into lcj VALUES(  
0004,'xiaoluo','男',18,'13520617734'),
(0002,'qq','man',18,'13212345432'),
(0003,'ww','gril',19,'13567890987');

#更新數據;將ID為3的姓名改為lcj
UPDATE lcj set name = 'lcj' WHERE id = 3;
#查看字典條數據
SELECT name from lcj where id = 2;
#查看所有數據
SELECT * from lcj
#刪除數據
DELETE from lcj WHERE id = 4;

   清空表:  

delete from 表名
truncate table 表名

   修改表:

添加列:alter table 表名 add 列名 類型
刪除列:alter table 表名 drop column 列名
修改列:
        alter table 表名 modify column 列名 類型;  -- 類型
        alter table 表名 change 原列名 新列名 類型; -- 列名,類型
 
添加主鍵:
        alter table 表名 add primary key(列名);
刪除主鍵:
        alter table 表名 drop primary key;
        alter table 表名  modify  列名 int, drop primary key;
 
添加外鍵:alter table 從表 add constraint 外鍵名稱(形如:FK_從表_主表) foreign key 從表(外鍵字段) references 主表(主鍵字段);
刪除外鍵:alter table 表名 drop foreign key 外鍵名稱
 
修改默認值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
刪除默認值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

   基本數據類型

  MySQL的數據類型大致分為:數值、時間和字符串;

  參考地址:http://www.runoob.com/mysql/mysql-data-types.html

  mysql其他操作:

    1、條件
        select * from 表 where id > 1 and name != 'alex' and num = 12;

        select * from 表 where id between 5 and 16;

        select * from 表 where id in (11,22,33)
        select * from 表 where id not in (11,22,33)
        select * from 表 where id in (select nid from 表)

    2、通配符
        select * from 表 where name like 'ale%'  - ale開頭的所有(多個字符串)
        select * from 表 where name like 'ale_'  - ale開頭的所有(一個字符)

    3、限制
        select * from 表 limit 5;            - 前5行
        select * from 表 limit 4,5;          - 從第4行開始的5行
        select * from 表 limit 5 offset 4    - 從第4行開始的5行

    4、排序
        select * from 表 order by 列 asc              - 根據 “列” 從小到大排列
        select * from 表 order by 列 desc             - 根據 “列” 從大到小排列
        select * from 表 order by 列1 desc,列2 asc    - 根據 “列1” 從大到小排列,如果相同則按列2從小到大排序

    5、分組
        select num from 表 group by num
        select num,nid from 表 group by num,nid
        select num,nid from 表  where nid > 10 group by num,nid order nid desc
        select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid

        select num from 表 group by num having max(id) > 10

        特別的:group by 必須在where之后,order by之前

    6、連表
        無對應關系則不顯示
        select A.num, A.name, B.name
        from A,B
        Where A.nid = B.nid

        無對應關系則不顯示
        select A.num, A.name, B.name
        from A inner join B
        on A.nid = B.nid

        A表所有顯示,如果B中無對應關系,則值為null
        select A.num, A.name, B.name
        from A left join B
        on A.nid = B.nid

        B表所有顯示,如果B中無對應關系,則值為null
        select A.num, A.name, B.name
        from A right join B
        on A.nid = B.nid

    7、組合
        組合,自動處理重合
        select nickname
        from A
        union
        select name
        from B

        組合,不處理重合
        select nickname
        from A
        union all
        select name
        from B

 

五、基於Pycharm中pymysql模塊實現mysql操作

  1、Pycharm安裝pymysql模塊  

  2、簡單使用pymysql某塊

  1)插入數據

  通過pymysql向遠程數據庫同時插入多條數據並打印插入數據條數

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lcj
import pymysql
#連接數據庫
conn = pymysql.connect(host='192.168.1.152',port= 3306,user = 'root',passwd='123123',db='test') #db:庫名
#創建游標
cur = conn.cursor()
#插入一條數據
# reCount = cur.excute('insert into lcj(name,age) values(%s,%s)',('ff',18))
#向test庫中的lcj表插入
# ret = cur.executemany("insert into lcj(name,tel)values(%s,%s)", [("kk",13212344321),("kw",13245678906)])
#同時向數據庫lcj表中插入多條數據
ret = cur.executemany("insert into lcj values(%s,%s,%s,%s,%s)", [(41,"xiaoluo41",'man',24,13212344332),
															  (42,"xiaoluo42",'gril',21,13245678948),
															  (43,"xiaoluo43",'gril',22,13245678949),
																 (44,"xiaoluo44",'main',24,13543245648)])
#提交
conn.commit()
#關閉指針對象
cur.close()
#關閉連接對象
conn.close()
#打印結果
print(ret)

   2)查詢數據

  在Pycharm控制台輸出lcj表中數據

# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lcj
import pymysql
#連接數據庫
conn = pymysql.connect(host='192.168.1.152',port= 3306,user = 'root',passwd='123123',db='test') #db:庫名
#創建游標
cur = conn.cursor()
#查詢lcj表中存在的數據
cur.execute("select * from lcj")
#fetchall:獲取lcj表中所有的數據
ret1 = cur.fetchall()
print(ret1)
print("----------------------")
#獲取lcj表中前三行數據
ret2 = cur.fetchmany(3)
print(ret2)
print("------------------------------")
#獲取lcj表中第一行數據
ret3= cur.fetchone()
print(ret3)
#同時向數據庫lcj表中插入多條數據
# ret = cur.executemany("insert into lcj values(%s,%s,%s,%s,%s)", [(41,"xiaoluo41",'man',24,13212344332),
# 															  (42,"xiaoluo42",'gril',21,13245678948),
# 															  (43,"xiaoluo43",'gril',22,13245678949),
# 																 (44,"xiaoluo44",'main',24,13543245648)])
#提交
conn.commit()
#關閉指針對象
cur.close()
#關閉連接對象
conn.close()

 注:在fetch數據時按照順序進行,可以使用cursor.scroll(num,mode)來移動游標位置,如:

  • cursor.scroll(1,mode='relative')  # 相對當前位置移動【1:表示向下移動一行,-1:表示向上移動一行
  • cursor.scroll(2,mode='absolute') # 相對絕對位置移動 【1:表示向上移動一行,-1:表示向下移動一行

  3)刪除數據  

# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lcj
import pymysql
#連接數據庫
conn = pymysql.connect(host='192.168.1.152',port= 3306,user = 'root',passwd='123123',db='test') #db:庫名
#創建游標
cur = conn.cursor()
#刪除cj表中數據
cur.execute("delete * from lcj")
#提交
conn.commit()
#關閉指針對象
cur.close()
#關閉連接對象
conn.close()

   4)修改表中的數據  

# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lcj
import pymysql
#連接數據庫
conn = pymysql.connect(host='192.168.1.152',port= 3306,user = 'root',passwd='123123',db='test') #db:庫名
#創建游標
cur = conn.cursor()
#將lcj表中id=3的name 修改為lcjj
cur.execute("UPDATE lcj set name = 'lcjj' WHERE id = 3")  #逼表中所有的操作都可以再此進行操作
#提交
conn.commit()
#關閉指針對象
cur.close()
#關閉連接對象
conn.close()

   5)fetch數據類型

  關於默認獲取的數據是元祖類型,如果想要或者字典類型的數據,即:  

# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lcj
import pymysql
#連接數據庫
conn = pymysql.connect(host='192.168.1.152',port= 3306,user = 'root',passwd='123123',db='test') #db:庫名
#設置游標類型,默認游標類型為元祖形式
#將游標類型設置為字典形式
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute("select * from lcj")  #逼表中所有的操作都可以再此進行操作
#將lcj表中所有數據以字典形式輸出
ret = cur.fetchall() 
print(ret)   #[{'age': 18, 'tel': '13520617734', 'name': 'xiaoluo', 'id': 1, 'sex': '?'},
#提交
conn.commit()
#關閉指針對象
cur.close()
#關閉連接對象
conn.close()

     繼續完善中 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM