pymsql是Python中操做MySQL的模塊,其使用方法和MySQLdb幾乎相同。python
下載安裝mysql
C:\Users\Administrator>pip install pymysql Collecting pymysql Downloading PyMySQL-0.7.11-py2.py3-none-any.whl (78kB) 38% |████████████▌ | 30kB 266kB/s eta 0:00:01 51% |████████████████▋ | 40kB 125kB/s eta 0:0 64% |████████████████████▊ | 51kB 156kB/s eta 77% |█████████████████████████ | 61kB 187kB/s 90% |█████████████████████████████ | 71kB 217 100% |████████████████████████████████| 81kB 233kB/s Installing collected packages: pymysql Successfully installed pymysql-0.7.11
首先導入這個模塊,以後鏈接上這個數據庫,建立遊標,而後設計交互式的操做數據庫,最後提交數據,關閉遊標,關閉鏈接sql
主要用到execute參數數據庫
#/usr/bin/env python import pymysql #建立鏈接 conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456",db="db1") #必須建立遊標(遊標幫着存儲數據,用來操做) cursor=conn.cursor() #執行sql,而且返回影響函數,可是數據庫尚未變動,也就是沒有提交 # effect_row=cursor.execute("update user set username='pyrene'") # effect_row=cursor.execute("INSERT INTO user(username,password) values('pyren','23')") # print(effect_row) #打印出受用戶註冊影響的信息條數 # 交互是讓用戶輸入數據 u=input(">>>") p=input(">>>") effect_row=cursor.execute("INSERT INTO user(username,password) values(%s,%s)",(u,p)) #這個是插入多行數據 # effect_row=cursor.executemany("INSERT INTO user(username,password) values(%s,%s)",[("aa","bb"),("cc","dd")]) #提交數據,否則沒法保存新建或者修改的數據 conn.commit() #關閉遊標 cursor.close() #關閉鏈接 conn.close()
fetchall:獲取全部數據,默認的獲取數據類型是元祖,若是想要字典類型的數據須要在建立右邊的時候在參數裏面寫入cursor=pymysql.cursor.DictCursoride
fetchone:獲取第一個數據(相似指針的形式)函數
fetchmany(size):依次移動(參數個指針)fetch
在fetch數據按照順序進行,可使用cursor.scroll(num.mode)來移動遊標位置,num若是爲正值那麼就往"位置"後面移動。若是爲負值那麼就往"位置"前面移動spa
#/usr/bin/env python import pymysql #建立鏈接 conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456",db="db1") #這裏用來指定遊標,讓下面的值以字典的形式返回 cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) effect_row=cursor.execute("select * from user where nid>%s order by nid desc" ,(7,)) result=cursor.fetchone()#獲取第一個數據 print(result) result=cursor.fetchone()#獲取第一個數據 print(result) result=cursor.fetchone()#獲取第二個數據 # result=cursor.fetchmany(1)#依次挪動(參數)個指針 print(result) cursor.scroll(-1,mode="relative") #把指針移動到當前指針的上一次位置負值往上移動,正值往下移動 result=cursor.fetchone()#獲取第一個數據 print(result) #關閉遊標 cursor.close() #關閉鏈接 conn.close()
用cursor.lastrowid獲取插入數據自增的位置設計
注意:若是用戶用executemany插入多個數據,那麼獲取的位置爲最後一個插入位置的數據指針
#/usr/bin/env python import pymysql #建立鏈接 conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456",db="db1") #這裏用來指定遊標,讓下面的值以字典的形式返回 cursor=conn.cursor() u=input(">>") p=input(">>") effect_raw=cursor.execute("insert into user(username,password) values(%s,%s)",(u,p)) conn.commit() print(cursor.lastrowid) #關閉遊標 cursor.close() #關閉鏈接 conn.close() # >>a # >>aa # 14