PyMySQL
v1.1.1
軟體包包含一個基於 PEP 249 的純 Python MySQL 和 MariaDB 用戶端程式庫。
包上傳到 PyPI 上。
您可以使用 pip 安裝它:
$ python3 -m pip install PyMySQL
要使用“sha256_password”或“caching_sha2_password”進行身份驗證,您需要安裝額外的依賴項:
$ python3 -m pip install PyMySQL[rsa]
要使用MariaDB的「ed25519」身份驗證方法,您需要安裝額外的依賴項:
$ python3 -m pip install PyMySQL[ed25519]
文件可線上取得:https://pymysql.readthedocs.io/
如需支持,請參閱 StackOverflow。
以下範例使用一個簡單的表格
CREATE TABLE ` users ` (
` id ` int ( 11 ) NOT NULL AUTO_INCREMENT,
` email ` varchar ( 255 ) COLLATE utf8_bin NOT NULL ,
` password ` varchar ( 255 ) COLLATE utf8_bin NOT NULL ,
PRIMARY KEY ( ` id ` )
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin
AUTO_INCREMENT = 1 ;
import pymysql . cursors
# Connect to the database
connection = pymysql . connect ( host = 'localhost' ,
user = 'user' ,
password = 'passwd' ,
database = 'db' ,
cursorclass = pymysql . cursors . DictCursor )
with connection :
with connection . cursor () as cursor :
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor . execute ( sql , ( '[email protected]' , 'very-secret' ))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection . commit ()
with connection . cursor () as cursor :
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor . execute ( sql , ( '[email protected]' ,))
result = cursor . fetchone ()
print ( result )
此範例將列印:
{ 'password' : 'very-secret' , 'id' : 1 }
PyMySQL 是根據 MIT 許可證發布的。請參閱許可證以了解更多資訊。