Python 3 进阶 —— 使用 PyMySQL 操作 MySQL
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Python 3 进阶 —— 使用 PyMySQL 操作 MySQL》,聊聊MySQL、python、pymysql,我们一起来看看吧!
PyMySQL 是一个纯 Python 实现的 MySQL 客户端操作库,支持事务、存储过程、批量执行等。
PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。
安装
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 |
| read_default_file | Specifies my.cnf file to read these parameters from under the [client] section. |
| conv | Conversion dictionary to use instead of the default one. This is used to provide custom marshalling and unmarshaling of types. |
| use_unicode | Whether or not to default to unicode strings. This option defaults to true for Py3k. |
| client_flag | Custom flags to send to MySQL. Find potential values in constants.CLIENT. |
| cursorclass | 设置默认的游标类型 |
| init_command | 当连接建立完成之后执行的初始化 SQL 语句 |
| connect_timeout | 连接超时时间,默认 10,最小 1,最大 31536000 |
| ssl | A dict of arguments similar to mysql_ssl_set()'s parameters. For now the capath and cipher arguments are not supported. |
| read_default_group | Group to read from in the configuration file. |
| compress | Not supported |
| named_pipe | Not supported |
| autocommit | 是否自动提交,默认不自动提交,参数值为 None 表示以服务器为准 |
| local_infile | Boolean to enable the use of LOAD DATA LOCAL command. (default: False) |
| max_allowed_packet | 发送给服务器的最大数据量,默认为 16MB |
| defer_connect | 是否惰性连接,默认为立即连接 |
| auth_plugin_map | A dict of plugin names to a class that processes that plugin. The class will take the Connection object as the argument to the constructor. The class needs an authenticate method taking an authentication packet as an argument. For the dialog plugin, a prompt(echo, prompt) method can be used (if no authenticate method) for returning a string from the user. (experimental) |
| server_public_key | SHA256 authenticaiton plugin public key value. (default: None) |
| 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) 批量执行 SQL
# 获取游标 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 等修改数据的语句需手动执行
cursor.lastrowid
查询数据
# 执行查询 SQL
cursor.execute('SELECT * FROM `users`')
# 获取单条数据
cursor.fetchone()
# 获取前N条数据
cursor.fetchmany(3)
# 获取所有数据
cursor.fetchall()
游标控制
所有的数据查询操作均基于游标,我们可以通过
cursor.scroll(1, mode='relative') # 相对当前位置移动 cursor.scroll(2, mode='absolute') # 相对绝对位置移动
设置游标类型
查询时,默认返回的数据类型为元组,可以自定义设置返回类型。支持5种游标类型:
- Cursor: 默认,元组类型
- DictCursor: 字典类型
- DictCursorMixin: 支持自定义的游标类型,需先自定义才可使用
- SSCursor: 无缓冲元组类型
- SSDictCursor: 无缓冲字典类型
无缓冲游标类型,适用于数据量很大,一次性返回太慢,或者服务端带宽较小时。源码注释:
Unbuffered Cursor, mainly useful for queries that return a lot of data, or for connections to remote servers over a slow network.Instead of copying every row of data into a buffer, this will fetch rows as needed. The upside of this is the client uses much less memory, and rows are returned much faster when traveling over a slow network
or if the result set is very big.There are limitations, though. The MySQL protocol doesn't support returning the total number of rows, so the only way to tell how many rows there are is to iterate over every row returned. Also, it currently isn't possible to scroll backwards, as only the current row is held in memory.
创建连接时,通过 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)
事务处理
- 开启事务
# 插入数据(元组或列表)
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),
])
参考资料
原文地址: https://shockerli.net/post/py...
更多文章请访问我的个人博客: https://shockerli.net
好了,本文到此结束,带大家了解了《Python 3 进阶 —— 使用 PyMySQL 操作 MySQL》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!
【Java猫说】项目架构的演进史(大型电商系列)
- 上一篇
- 【Java猫说】项目架构的演进史(大型电商系列)
- 下一篇
- 大数据集群搭建 - 2. CDH集群安装 - NTP,MYSQL,nginx安装
-
- 数据库 · MySQL | 40分钟前 |
- MySQL CTE 多次引用时为什么可能重复物化
- 237浏览 收藏
-
- 数据库 · MySQL | 3小时前 | MySQL · 执行计划 · 索引优化 · mysql explain OR条件 Index Merge
- MySQL OR 条件什么时候会选择 Index Merge
- 373浏览 收藏
-
- 数据库 · MySQL | 5小时前 |
- MySQL 事务隔离级别下普通 SELECT 为什么看不到新提交
- 385浏览 收藏
-
- 数据库 · MySQL | 6小时前 | MySQL · 索引 · 性能优化 · 执行计划 · mysql explain optimizer hint FORCE INDEX USE INDEX
- MySQL optimizer hint 和 FORCE INDEX 怎么选择
- 478浏览 收藏
-
- 数据库 · MySQL | 7小时前 | MySQL · explain · 性能分析 · JSON执行计划 · 嵌套循环 · mysql 执行计划 EXPLAIN FORMAT=JSON nested_loop 查询成本
- MySQL EXPLAIN FORMAT=JSON 怎么查看嵌套循环成本
- 166浏览 收藏
-
- 数据库 · MySQL | 13小时前 |
- MySQL collation 不一致导致 JOIN 报错怎么统一
- 446浏览 收藏
-
- 数据库 · MySQL | 22小时前 |
- MySQL 递归 CTE 生成日期序列时为什么列类型会截断
- 104浏览 收藏
-
- 数据库 · MySQL | 1天前 |
- MySQL 递归 CTE 遍历树数据时怎么防止无限循环
- 142浏览 收藏
-
- 数据库 · MySQL | 1天前 |
- MySQL invisible index 如何安全观察索引下线影响
- 300浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 63次使用
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 224次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 148次使用
-
- AI Prompt Library
- 探索AI Prompt Library免费资源库,涵盖营销、写作及多场景AI提示词。兼容ChatGPT、Claude等工具,一键复制优化输出,提升工作效率。
- 81次使用
-
- Generrated
- Generrated汇集9300+张DALL·E生成图像及对应提示词,支持查看完整图集、对比DALL·E 2与3版本差异,是AI绘图新手学习Prompt设计与获取创作灵感的实用工具。
- 58次使用
-
- MySQL 明明加了索引,为什么查询还是很慢?先查这 6 个点
- 2026-06-27 374浏览
-
- golang MySQL实现对数据库表存储获取操作示例
- 2022-12-22 499浏览
-
- golang 基于 mysql 简单实现分布式读写锁
- 2023-01-07 384浏览
-
- 详解如何利用GORM实现MySQL事务
- 2023-01-07 184浏览
-
- Go语言实现操作MySQL的基础知识总结
- 2023-01-23 265浏览

