来源: Shocker 连接:
https://shockerli.net/post/python3-pymysql/html
PyMySQL 是一个纯 Python 实现的 MySQL 客户端操做库,支持事务、存储过程、批量执行等。python
PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。mysql
安装sql
pip install PyMySQL
建立数据库链接数据库
import pymysql connection = pymysql.connect(host='localhost', port=3306, user='root', password='root', db='demo', charset='utf8')
参数列表:安全
参数 描述 host 数据库服务器地址,默认 localhost user 用户名,默认为当前程序运行用户 password 登陆密码,默认为空字符串 database 默认操做的数据库 port 数据库端口,默认为 3306 bind_address 当客户端有多个网络接口时,指定链接到主机的接口。参数能够是主机名或IP地址。 unix_socket unix 套接字地址,区别于 host 链接 read_timeout 读取数据超时时间,单位秒,默认无限制 write_timeout 写入数据超时时间,单位秒,默认无限制 charset 数据库编码 sql_mode 指定默认的 SQL_MODE cursorclass 设置默认的游标类型 init_command 当链接创建完成以后执行的初始化 SQL 语句 connect_timeout 链接超时时间,默认 10,最小 1,最大 31536000 autocommit 是否自动提交,默认不自动提交,参数值为 None 表示以服务器为准 local_infile Boolean to enable the use of LOAD DATA LOCAL command. (default: False) max_allowed_packet 发送给服务器的最大数据量,默认为 16MB defer_connect 是否惰性链接,默认为当即链接 db 参数 database 的别名 passwd 参数 password 的别名 binary_prefix Add _binary prefix on bytes and bytearray. (default: False)
执行 SQL服务器
cursor.execute(sql, args) 执行单条 SQL网络
# 获取游标 cursor = connection.cursor() # 建立数据表 effect_row = cursor.execute(''' CREATE TABLE `users` ( `name` varchar(32) NOT NULL, `age` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ''') # 插入数据(元组或列表) effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18)) # 插入数据(字典) info = {'name': 'fake', 'age': 15} effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%(name)s, %(age)s)', info) connection.commit()
executemany(sql, args) 批量执行 SQLsocket
# 获取游标 cursor = connection.cursor() # 批量插入 effect_row = cursor.executemany( 'INSERT INTO `users` (`name`, `age`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [ ('hello', 13), ('fake', 28), ]) connection.commit()
注意:INSERT、UPDATE、DELETE 等修改数据的语句需手动执行connection.commit()完成对数据修改的提交。post
获取自增 ID
cursor.lastrowid
查询数据
# 执行查询 SQL cursor.execute('SELECT * FROM `users`') # 获取单条数据 cursor.fetchone() # 获取前N条数据 cursor.fetchmany(3) # 获取全部数据 cursor.fetchall()
游标控制
全部的数据查询操做均基于游标,咱们能够经过cursor.scroll(num, mode)控制游标的位置
cursor.scroll(1, mode='relative') # 相对当前位置移动 cursor.scroll(2, mode='absolute') # 相对绝对位置移动
设置游标类型
查询时,默认返回的数据类型为元组,能够自定义设置返回类型。支持5种游标类型:
无缓冲游标类型,适用于数据量很大,一次性返回太慢,或者服务端带宽较小时。
建立链接时,经过 cursorclass 参数指定类型:
connection = pymysql.connect(host='localhost', user='root', password='root', db='demo', charset='utf8', cursorclass=pymysql.cursors.DictCursor)
也能够在建立游标时指定类型:
cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
事务处理
防 SQL 注入
参数化语句 支持传入参数进行自动转义、格式化 SQL 语句,以免 SQL 注入等安全问题。
# 插入数据(元组或列表)
effect_row = cursor.execute('INSERT INTO users
(name
, age
) VALUES (%s, %s)', ('mary', 18))
# 插入数据(字典)
info = {'name': 'fake', 'age': 15}
effect_row = cursor.execute('INSERT INTO users
(name
, age
) VALUES (%(name)s, %(age)s)', info)
# 批量插入
effect_row = cursor.executemany(
'INSERT INTO users
(name
, age
) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [
('hello', 13),
('fake', 28),
])
参考资料