Pymysql简单使用

写代码的时候,操作数据库是必须的。之前都是能用就可以,今天得好好总结一下,这里用 pymysql 举例。

什么是Pymysql

纯 Python 实现的一个 MySQL 客户端协议,兼容几乎所有的 MySQL 数据库。

简单使用

安装
1
pip install pymysql
具体例子

先来看看官网给我们的例子,插入&查询一条记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import pymysql

# 建表
'''
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=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;
'''

# connecition 信息
connection = pymysql.connect(host = 'localhost',
user = 'root',
password = 'xxx',
db = 'demo',
charset = 'utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
try:
# 使用 with 的好处在于 with 结束后会自动关闭 cursor
# 插入数据
with connection.cursor() as cursor:
sql = "insert into users (`email`,`password`) values (%s,%s)"
cursor.execute(sql,('zy@xx.com','123456'))
# 连接默认不开启 autocommit,所以需要我们自己去 commit
connection.commit()

# 查询数据
with connection.cursor() as cursor:
sql = 'select `id` , `email` , `password` from `users` where `email` = %s '
cursor.execute(sql,('zy@xx.com'))
res = cursor.fetchone() # 这里已经提交了
print(res)
finally:
connection.close()

输出则是:(1, 'zy@xx.com', '123456')

连接对象
1
pymysql.connections.Connection(host=None, user=None, password='', database=None, port=0, unix_socket=None, charset='', sql_mode=None, read_default_file=None, conv=None, use_unicode=None, client_flag=0, cursorclass=<class 'pymysql.cursors.Cursor'>, init_command=None, connect_timeout=10, ssl=None, read_default_group=None, compress=None, named_pipe=None, autocommit=False, db=None, passwd=None, 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)

初始化 connection 对象时有很多参数,这里我们说几个比较常用的,具体信息可以参考官方文档

  • host - 数据库服务器地址
  • user - 用户名
  • password ( passwd ) - 密码,默认为空字符串
  • database ( db ) - 操作的数据库
  • port - MySQL使用的端口,默认3306
  • charset - 想要使用的数据库编码
  • cursorclass - 默认的游标类型
  • connect_timeout - 连接超时时间
  • autocommit - 是否自动提交,默认为否
  • local_infile - 是否允许可以load本地数据

一般我们使用 cursor()commit() 方法

获取游标

cursor=connection.cursor(),有了 cursor 对象之后我们才可以进行各种增删改查等数据库操作,其对我们最重要的方法是 execute()fetch() 方法,因为我们所有对数据的操作都是通过他们执行的。sizefetchmany()

cursor 可以通过创建时指定类型,有

  • Cursor - 元组类型
  • SSCursor - 无缓冲元组类型
  • DictCursor - 字典类型
  • SSDictCursor - 无缓冲字典类型
增删改查
查询数据

还是之前的例子

1
2
3
4
with connection.cursor() as cursor:
sql = 'select `id` , `email` , `password` from `users` where `email` = %s '
cursor.execute(sql,('zy@xx.com'))
res = cursor.fetchone()

不过还有几个其他的方法:

  • fetchall() - 取回全部数据
  • fetchmany(size) - 取回一部分数据,由 size 决定

两者都返回一个 list 对象,不过我以为会是一个生成器的…

增删改数据

使用 cursor.execute(),方法,这个写好 sql 就好,不过这些操作都需要 cursor.commit() 操作才会生效。还有一个 cursor.executemany() 的方法,使用极少极少。

参考

  1. PyMySQL-PyPi
  2. PyMySQL官方文档