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 许可证发布的。请参阅许可证了解更多信息。