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, ('[email protected]','very-secret'))
# 连接不会自动提交,所以你想下面要调用 commit 方法,存储对数据库的改动
connection.commit()
with connection.cursor() ascursor:
sql="SELECT id, password FROM users WHERE email=%s"cursor.execute(sql, ('[email protected]',))
# 获取一条的纪录
result=cursor.fetchone()
print(result)
# 结果输出:{'password': 'very-secret', 'id': 1}
finally:
connection.close()
# 操作完数据库一要记得调用 close 方法,关闭连接