一、機制
pymysql庫的操作有點類似os.system(),需要直接給出mysql語句,會返回影響行數、數據等信息。
二、安裝庫及創建數據庫、表
PyMySQL-0.9.3 (至少安裝這個版本以上,否則會在connect時報錯)
爲進行試驗,繞開一些權限的問題,創建了新的數據庫及表
create database test_databases;
create table newtable(key1 char(20) NOT NULL,key2 int(11) NOT NULL);
這裏實驗的表名爲newtable,具體信息如下:
三、基本操作
注意對一行操作和對N行操作的不同。
注意遊標的移動及類型。
import pymysql
# 創建連接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='3gynj20J', db='test_databases')
# # 創建遊標,返回元祖型數據
# cursor = conn.cursor()
# 創建遊標,返回字典型數據
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#增1
effect_row = cursor.execute("insert into newtable values('a',1)")
print(effect_row)
#增N
effect_row = cursor.executemany("insert into newtable values(%s,%s)",[('b',2),('c',3)])
print(effect_row)
#改
effect_row = cursor.execute("update newtable set key1='A' where key2=1")
print(effect_row)
# 注意mysql的fetch*會使cursor查一條少一條,遊標自動向後移動,row_1和row_N是不重複的
#查1
cursor.execute("select * from newtable")
row_1 = cursor.fetchone()
print(row_1)
#查N
row_N = cursor.fetchmany(2)
#查all
row_all = cursor.fetchall()
print(row_1,row_N,row_all)
# print(cursor) # 是一個對象,不是list,<pymysql.cursors.Cursor object at 0x0000000002A51AC8>
# for i in cursor:
# print(i)
#查某個位置開始的幾個
# cursor.scroll(1,mode='relative') # 相對當前位置移動
cursor.scroll(2,mode='absolute') # 相對絕對位置移動
row_1 = cursor.fetchone()
print(row_1)
四、常見報錯
1、KeyError: 255
安裝更高版本的pymysql。pip install --upgrade PyMySQL
https://www.jianshu.com/p/f69e846558ab
2、pymysql.err.OperationalError: (1142, "UPDATE command denied to user 'root'@'localhost' for table 'status_by_user'")
對於mysql安裝時自帶的數據庫及表,可以進行查詢,但無法修改的問題,可以自己創建數據庫及表。