纯python mysql驱动程序
PyMySQL的Python项目详细描述
pymysql
这个包包含一个基于PEP 249的纯python mysql客户端库。
大多数公共api都与mysqlclient和mysqldb兼容。
注意:pymysql不支持低级api,mysql提供类似于data-seek的api。 存储结果,并使用结果。您应该使用PEP 249中定义的高级api。 但是,由于PEP 249不包括 他们的用例。
Installation
包上载于PyPI。
您可以使用pip安装它:
$ python3 -m pip install PyMySQL
要使用“SHA256密码”或“缓存SHA26密码”进行身份验证, 您需要安装其他依赖项:
$ python3 -m pip install PyMySQL[rsa]
Example
下面的示例使用一个简单的表
CREATETABLE`users`(`id`int(11)NOTNULLAUTO_INCREMENT,`email`varchar(255)COLLATEutf8_binNOTNULL,`password`varchar(255)COLLATEutf8_binNOTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBDEFAULTCHARSET=utf8COLLATE=utf8_binAUTO_INCREMENT=1;
importpymysql.cursors# Connect to the databaseconnection=pymysql.connect(host='localhost',user='user',password='passwd',db='db',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)try:withconnection.cursor()ascursor:# Create a new recordsql="INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"cursor.execute(sql,('webmaster@python.org','very-secret'))# connection is not autocommit by default. So you must commit to save# your changes.connection.commit()withconnection.cursor()ascursor:# Read a single recordsql="SELECT `id`, `password` FROM `users` WHERE `email`=%s"cursor.execute(sql,('webmaster@python.org',))result=cursor.fetchone()print(result)finally:connection.close()
此示例将打印:
{'password':'very-secret','id':1}
Resources
- DB-API 2.0:https://www.python.org/dev/peps/pep-0249/
- mysql参考手册:https://dev.mysql.com/doc/
- MySQL客户端/服务器协议: https://dev.mysql.com/doc/internals/en/client-server-protocol.html
- mysql社区slack中的“connector”通道: https://lefred.be/mysql-community-on-slack/
- pymysql邮件列表:https://groups.google.com/forum/#!forum/pymysql-users
License
pymysql是在mit许可下发布的。有关详细信息,请参见许可证。