源碼中對(duì) PyMySQL 的定義:
PyMySQL: A pure-Python MySQL client library
數(shù)據(jù)庫(kù)的連接
手工關(guān)閉數(shù)據(jù)庫(kù)的 connection
import pymysql
# 連接數(shù)據(jù)庫(kù)一種比較優(yōu)雅的寫(xiě)法
config = {
'host': 'localhost',
'user': 'root',
'password': 'xx',
'database': 'dbx',
'charset': 'utf8mb4',
'port': 3306 # 注意端口為int 而不是str
}
connection = pymysql.connect(**config)
cursor = connection.cursor()
try:
# 創(chuàng)建一張表
c_sql = '''CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`employee_id` int NOT NULL,
PRIMARY KEY (`id`))
ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
AUTO_INCREMENT=1'''
cursor.execute(c_sql)
# 插入一條記錄
i_sql = "INSERT INTO `users` (`email`, `password`) VALUES ('cancy', 'very-secret', 28)"
cursor.execute(i_sql)
# 在同一個(gè)cursor上統(tǒng)一提交
connection.commit()
except Exception as e:
connection.rollback()
print('Failed:', e)
finally:
cursor.close()
connection.close()
executemany 方法
同時(shí)添加多個(gè)數(shù)據(jù)時(shí)使用 executemany 方法
try:
with connection.cursor() as cursor:
# 在寫(xiě)sql語(yǔ)句時(shí),不管字段為什么類型, 占位符統(tǒng)一使用 %s, 且不能帶引號(hào)
sql = "INSERT INTO `users` (`username`, `password`, `employee_id`) VALUES (%s, %s, %s)"
cursor.executemany(sql, [('sam', 'secret1', 29), ('Bob', 'secret2', 32)])
connection.commit()
finally:
connection.close()
但是值得注意的有兩點(diǎn):
- 在寫(xiě)sql語(yǔ)句時(shí)序无,不管字段為什么類型, 占位符統(tǒng)一使用 %s, 且不能帶引號(hào)
- 添加數(shù)據(jù)的格式必須為 list[tuple(), tuple(), tuple()] 或者 tuple(tuple(), tuple(), tuple())
- 在資源足夠的情況下先誉,當(dāng)然可以將需要插入的所有數(shù)據(jù)一次性全部放入 list 或者tuple 中玛痊,然后執(zhí)行 executemany 方法传趾,但實(shí)際中這種方法是不可取的晤郑,因?yàn)榉?wù)端能夠接收的最大數(shù)據(jù)包是有限制的
DictCursor
游標(biāo)類型有 Cursor永脓、DictCursor袍辞、SSCursor、SSDictCursor等4種類型常摧,但是常用的是前面兩種
- Cursor默認(rèn)類型搅吁,查詢返回 list,如果是默認(rèn)Cursor落午,那么在 cursorclass 中就不需要指定
- DictCursor類型谎懦,查詢返回dict,包括屬性名
import pymysql.cursors
# 連接數(shù)據(jù)庫(kù)
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
query查詢
# 引入這個(gè)模塊就ok
import pymysql.cursors
config = {
'host': '127.0.0.1',
'port': 3306,
'user': 'user',
'password': 'passwd',
'database': 'db',
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.Cursor,
}
# pymysql.cursors.Cursor 或者 pymysql.cursors.DictCursor
# 連接數(shù)據(jù)庫(kù)
connection = pymysql.connect(**config)
try:
with connection.cursor() as cursor:
sql = 'SELECT * FROM commodity WHERE price > 100 ORDER BY price'
count = cursor.execute(sql) # 影響的行數(shù)
print(count)
results = cursor.fetchall() # 取出所有行
for row in results: # 打印結(jié)果
print(row)
# 查詢不是事物的溃斋,不需要commit
# connection.commit()
except Exception as e:
# connection.rollback() # 對(duì)于事物型的操作界拦,比較適合commit后,如果失敗則回滾梗劫,在本例中僅是查詢享甸,無(wú)須回滾
logger.info(e)
finally:
connection.close()
關(guān)于fetch結(jié)果:
- cursor.fetchone() # 獲取1條數(shù)據(jù)
- cursor.fetchmany(n) # 獲取n條數(shù)據(jù)
- cursor.fetchall() # 獲取所有數(shù)據(jù)
delete 與 update 操作
delete和update操作顯然都是事物的,下面以delete為例梳侨,偽碼如下:
cursor = connection.cursor()
d_sql = 'DELETE FROM students WHERE age < 24'
try:
cursor.execute(d_sql)
connection.commit()
logger.info('delete success')
except:
connection.rollback()
logger.info('delete error')
print('delete rowcount = %d' %cursor.rowcount)
cursor游標(biāo)的移動(dòng)
connection = pymysql.connect(**config)
try:
with connection.cursor() as cursor:
sql = 'SELECT * FROM commodity WHERE price > 100 ORDER BY price'
cursor.execute(sql)
result1 = cursor.fetchone() # 取出第一個(gè)結(jié)果
result2 = cursor.fetchall() # 執(zhí)行了上述代碼后蛉威,游標(biāo)會(huì)向下移動(dòng)一個(gè),此時(shí)獲取到的是剩下n-1個(gè)結(jié)果
for row in result2: # 打印結(jié)果
print(row)
except Exception as e:
logger.info(e)
finally:
connection.close()
cursor.scroll(0, mode = ‘a(chǎn)bsolute’)
相對(duì)于絕對(duì)位置移動(dòng)走哺,例如在上例中蚯嫌,使用了 fetchone之后,游標(biāo)向下移動(dòng)了一個(gè)位置丙躏,要想 fetchall 得到全部的結(jié)果齐帚,此時(shí)可以使用 cursor.scroll(0, mode = ‘a(chǎn)bsolute’) 將游標(biāo)主動(dòng)移動(dòng)到絕對(duì)位置為0的位置,然后再使用 fetchallcursor.scroll(1, mode = ‘relative’)
相對(duì)于當(dāng)前位置移動(dòng)
MySQL連接池
https://blog.csdn.net/kai404/article/details/78900220
https://github.com/jkklee/pymysql-pool