Python|pymysql 官方文档整理(样例 + API 手册)

1 安装方法
直接使用 pip 安装 PyMySQL 即可:

pip install PyMySQL
1
PyMySQL 对 Python 版本要求:CPython >= 3.6 或最新版的 PyPy3

PyMySQL 对数据库版本要求:MySQL >= 5.6 或 MariaDB >= 10.0

2 样例
样例的数据准备
在本地 MySQL 的 test 数据库中,使用数据库终端创建表 users 用于测试,建表语句如下:

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 ;
1
2
3
4
5
6
7
样例
导入 pymysql 包:

import pymysql.cursors
1
连接到 MySQL 数据库:

# Connect to the database
connection = pymysql.connect(host='localhost',
port=3306,
user='root',
password='123456',
database='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
1
2
3
4
5
6
7
8
执行 INSERT INTO 语句插入一条记录,然后再执行 SELECT 语句读取刚才插入的记录。因为 connection 不会自动 commit,所以需要手动调用 connection.commit():

with connection:
with connection.cursor() as cursor:
# Create a new record
sql = "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()

with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
执行上述样例,会在控制台中打印:

{'id': 1, 'password': 'very-secret'}
1
3 相关引用
DB-API 2.0: http://www.python.org/dev/peps/pep-0249

MySQL Reference Manuals: http://dev.mysql.com/doc/

MySQL client/server protocol: http://dev.mysql.com/doc/internals/en/client-server-protocol.html

PyMySQL mailing list: https://groups.google.com/forum/#!forum/pymysql-users

4 Connection 对象
官方文档地址:https://pymysql.readthedocs.io/en/latest/modules/connections.html(Connection 对象文档)

到 MySQL 服务器的 Socket 连接对象。

建议通过调用 pymysql.connect() 方法构造 Connection 实例。

4.1 原型
pymysql.connections.Connection(*, user=None, password='', host=None, database=None, unix_socket=None, port=0, charset='', sql_mode=None, read_default_file=None, conv=None, use_unicode=True, client_flag=0, cursorclass=<class 'pymysql.cursors.Cursor'>, init_command=None, connect_timeout=10, read_default_group=None, autocommit=False, local_infile=False, max_allowed_packet=16777216, defer_connect=False, auth_plugin_map=None, read_timeout=None, write_timeout=None, bind_address=None, binary_prefix=False, program_name=None, server_public_key=None, ssl=None, ssl_ca=None, ssl_cert=None, ssl_disabled=None, ssl_key=None, ssl_verify_cert=None, ssl_verify_identity=None, compress=None, named_pipe=None, passwd=None, db=None)
1
4.2 常用参数
host:MySQL 服务器的地址
port:MySQL 服务器的端口号(默认为 3306)
user:登录的用户名
password:登录的密码
database:使用 USE [数据库名称] 指定当前数据库,如果不指定的话就相当于没有执行 USE [数据库名称] 指定当前数据库
connect_timeout:连接数据库的超时时间(默认为 10 秒)
read_timeout:从连接中读取数据的超时时间(默认没有超时时间)
write_timeout:向连接中写入数据的超时时间(默认没有超时时间)
charset:使用的编码集
4.3 常用方法
begin():开始事务
close():关闭连接
当连接已经被关闭时抛出异常
commit():将更改提交到稳定存储
cursor(cursor=None):创建一个新的 Cursor 用于执行 SQL 语句
cursor 参数:创建的 Cursor 的类型
open:如果连接仍然处于开启状态则返回 True
ping(reconnect=True):检查服务器是否仍然存活
reconnect 参数:如果连接已别关闭,是否重新连接
当连接已经关闭且 reconnect=False 时抛出异常
rollback():回滚当前事务
select_db(db):指定当前数据库
db 参数:数据库名称
show_warnings():发送 SHOW WARNINGS 语句
5 Cursor 对象
官方文档地址:https://pymysql.readthedocs.io/en/latest/modules/cursors.html (Cursor 对象文档)

5.1 pymysql.cursors.Cursor
用于与数据库进行交互的对象。

不要自己创建一个 Cursor 的实例,而是通过调用 connections.Connection.cursor() 来构造。

5.1.1 原型
pymysql.cursors.Cursor(connection)
1
5.1.2 常用方法
callproc(procname, args=()):执行存储过程 procname,并传入参数 args
close():待耗尽剩余数据后关闭 Cursor 对象
execute(query, args=None):执行 SQL 语句
query 参数:待执行的 SQL 语句
args 参数:SQL 语句所需的参数(如 args 为列表或元组,则 query 中需包含 %s;如 args 为字典,则 query 中需包含 %(name)s)
返回被影响的行数
executemany(query, args):使用多条数据执行 SQL 语句(遍历所有参数执行 SQL 语句,通常用于包含多行的 INSERT 语句和 REPLACE 语句)
query 参数:待执行的 SQL 语句
args 参数:SQL 语句所需的参数(列表、元组或字典的列表或元组;列表或元组中每个元素的用法与 execute 一致)
如果有被影响的行,则返回被影响的行数
fetchall():返回结果中的所有行
fetchmany(size=None):返回结果中的指定数量行
fetchone():返回结果中的下一行
max_stmt_length = 1024000:executemany() 生成的 SQL 语句的最大长度
mogrify(query, args=None):返回将通过调用 execute() 方法发送到数据库的实际字符串
query 参数:待执行的 SQL 语句
args 参数:SQL 语句所需的参数(如 args 为列表或元组,则 query 中需包含 %s;如 args 为字典,则 query 中需包含 %(name)s)
实际的查询语句字符串
setinputsizes(*args):没有意义
setoutputsizes(*args):没有意义
5.2 pymysql.cursors.SSCursor(connection)
无缓冲游标。主要适用于返回大量数据的查询或通过缓慢网络连接远程服务器。与将每一行数据复制到缓冲区不同,无缓冲游标将在需要时才获取对应行。

这样的好处是:

客户端使用的内存更少
当网速慢或结果集非常大时,行可以更快地开始返回
这样的限制是:

因为 MySQL 协议不支持返回总行数,所以只能通过遍历每一行来确定一共有多少行
因为在内存中只保留当前行,所以不支持反向滚动
5.2.1 原型
pymysql.cursors.SSCursor(connection)
1
5.2.2 常用方法
close():待耗尽剩余数据后关闭 Cursor 对象
fetchall():返回结果中的所有行;因为这是有 buffer 的,所以对数据量大的查询用处不大
fetchall_unbuffered():返回结果中的所有行作为一个生成器返回(虽然这不是标准的做法,但是对于数据量大的查询来说,将所有结果返回到列表中并不合理)
fetchmany(size=None):返回结果中的指定数量行
fetchone():返回结果中的下一行
read_next():读取结果中的下一行
5.3 pymysql.cursors.DictCursor(connection)
将结果作为字典返回的游标。

5.4 mysql.cursors.SSDictCursor(connection)
将结果作为字典返回的无缓冲游标。
————————————————


原文链接:https://blog.csdn.net/Changxing_J/article/details/132893956

posted on 2024-09-24 12:28  liufeng  阅读(183)  评论(0)    收藏  举报

导航