https://github.com/PyMySQL/PyMySQL
PyMySQL:純 pyton 寫的 mysql 庫,純 python 的好處就是可以運行在任何裝有 python 解釋器(CPython、PyPy、IronPython)的平臺上。相對于MySQLdb性能幾乎一樣,使用方法也一樣,但是** PyMySQL 安裝方法極其簡單**——pip install PyMySQL,PyMySQL 使用示例代碼:
# 下面為例子需要的數據庫的建表語句
CREATE TABLE users (
id int( 11 ) NOT NULL AUTO_INCREMENT,
email varchar( 25 5) COLLATE utf8_bin NOT NULL,
password varchar( 255 ) COLLATE utf8_bin NOT NULL,
PRIMARY KEY ( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;
# -*- coding: utf-8 -*-
import pymysql.cursors# 連接數據庫
connection = pymysql.connect( host='localhost',?user='user',?password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
try:
? ? with connection.cursor() as cursor:
? ? # 創建一個新的紀錄
? ? ? ? sql="INSERT INTO users ( email, password ) ?VALUES (%s,%s)"
? ? ? ? cursor.execute(sql, ('webmaster@python.org','very-secret'))
? ? # 連接不會自動提交,所以你想下面要調用 commit 方法,存儲對數據庫的改動
? ? connection.commit()?
? ? with connection.cursor() ascursor:
? ? ? ? sql="SELECT id, password FROM users WHERE email=%s"cursor.execute(sql, ('webmaster@python.org',))
# 獲取一條的紀錄
? ? ? ? result=cursor.fetchone()
? ? ? ? print(result)
# 結果輸出:{'password': 'very-secret', 'id': 1}
finally:
? ? connection.close()
# 操作完數據庫一要記得調用 close 方法,關閉連接