Python 3 进阶 —— 使用 PyMySQL 操作 MySQL
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 等修改数据的语句需手动执行connection.commit()完成对数据修改的提交。
获取自增 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种游标类型:
- 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)
事务处理
开启事务
connection.begin()提交修改
connection.commit()回滚事务
connection.rollback()
防 SQL 注入
转义特殊字符
connection.escape_string(str)参数化语句
支持传入参数进行自动转义、格式化 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),
])
参考资料
个人博客同步地址:
https://shockerli.net/post/python3-pymysql/
Python 3 进阶 —— 使用 PyMySQL 操作 MySQL的更多相关文章
- pymysql操作mysql
一.使用PyMySQL操作mysql数据库 适用环境 python版本 >=2.6或3.3 mysql版本>=4.1 安装 可以使用pip安装也可以手动下载安装.使用pip安装,在命令行执 ...
- Python 3.2: 使用pymysql连接Mysql
在python 3.2 中连接MYSQL的方式有很多种,例如使用mysqldb,pymysql.本文主要介绍使用Pymysql连接MYSQL的步骤 1 安装pymysql · ...
- python 3.6 +pyMysql 操作mysql数据库
版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...
- python使用pymysql操作mysql数据库
1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...
- flask + pymysql操作Mysql数据库
安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...
- PyMySQL操作mysql数据库(py3必学)
一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...
- 使用pymysql操作mysql数据库
PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...
- pymysql操作mysql数据库
1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...
- pymysql操作mysql的脚本示例
#!/usr/bin/env python#-*- coding:UTF-8 -*- from multiprocessing import Process , Queuefrom queue imp ...
随机推荐
- (PMP)第9章-----项目资源管理
9.1 规划资源管理 数据表现: 1.层级型(高层次的角色):工作分解结构,组织分解结构,资源分解结构 2.责任分配矩阵:RAM,RACI,执行,负责,咨询,知情(只有一个A) 3.文本型(记录详细职 ...
- IPC,Hz(Hertz) and Clock Speed
How do we measure a CPU's work? Whether it's fast or not depends on three factors: IPC, Hz, Clock sp ...
- azkaban disable 停用部分工作流
在使用azkaban作为调度工具的时候,难免遇到只需要跑工作流某部分的情况,这时需要用到停用部分工作的操作, 如图:
- Vuejs——(6)Vuejs与form元素
版权声明:出处http://blog.csdn.net/qq20004604 目录(?)[+] 资料来于官方文档: http://cn.vuejs.org/guide/forms.html 本 ...
- C++回调:利用Sink
Sink的本质是利用C++的封装.继承.多态的面向对象来实现,从实现角度来说,更优于函数指针回调: // cbBysink.cpp : Defines the entry point for the ...
- ReactNative学习笔记(六)集成视频播放
概述 视频播放可以自己写原生代码实现,然后注入JS.如果对视频播放没有特殊要求的话,可以直接使用现成插件. 到官方推荐的插件网站搜索找到下载量第一的插件:react-native-video. 安装 ...
- 接之前的文章,VS2017中使用Spring.NET配置以及使用方法(framework4.6.1超详细)
众所周知,Spring在java中是很常见的框架,Spring.Net虽然体积比较大,但是功能相对齐全,本文介绍在VS2017 .Net FrameWork 4.6.1环境下,如何快速使用Spring ...
- 骚年,看我如何把 PhantomJS 图片的 XSS 升级成 SSRF/LFR
这篇文章实在是太好了,我看了好几篇,所以极力推荐给大家 原文地址 http://buer.haus/2017/06/29/escalating-xss-in-phantomjs-image-ren ...
- 什么是CDN及CDN加速原理
目录 CDN是什么? CDN的相关技术 负载均衡技术 动态内容分发与复制技术 缓存技术 谁需要CDN? CDN的不足 随着互联网的发展,用户在使用网络时对网站的浏览速度和效果愈加重视,但由于网民数量激 ...
- 精通Linux
1, linux 启动流程,详细 2,grub , grub2 3, 文件系统,不同文件系统的特性 ext3 , ext 4 ,xfs 4, 不同目录的作用, 分区 5,用户管理 6,文件权限,目录挂 ...