Python 3 进阶 —— 使用 PyMySQL 操作 MySQL

摘要:
PyMySQL是一个纯Python实现的MySQL客户端操作库,支持事务、存储过程、批处理执行等。PyMySQL遵循Python数据库API v2.0规范,并包含纯Python MySQL客户端库。安装pipingsstallPyMySQL以创建数据库连接importpymysqlconnection=pymysqlConnect参数列表:参数描述主机数据库服务器地址,默认localhostuser用户名,当前程序运行用户的默认密码登录密码,默认空字符串数据库默认操作数据库端口数据库端口,默认3306bind_Address指定客户端具有多个网络接口时要连接到主机的接口。支持五种游标类型:游标:默认,元组类型DictCursor:字典类型DictCsorMixin:支持用户定义的游标类

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_socketunix 套接字地址,区别于 host 连接
read_timeout读取数据超时时间,单位秒,默认无限制
write_timeout写入数据超时时间,单位秒,默认无限制
charset数据库编码
sql_mode指定默认的 SQL_MODE
read_default_fileSpecifies my.cnf file to read these parameters from under the [client] section.
convConversion dictionary to use instead of the default one. This is used to provide custom marshalling and unmarshaling of types.
use_unicodeWhether or not to default to unicode strings. This option defaults to true for Py3k.
client_flagCustom flags to send to MySQL. Find potential values in constants.CLIENT.
cursorclass设置默认的游标类型
init_command当连接建立完成之后执行的初始化 SQL 语句
connect_timeout连接超时时间,默认 10,最小 1,最大 31536000
sslA dict of arguments similar to mysql_ssl_set()'s parameters. For now the capath and cipher arguments are not supported.
read_default_groupGroup to read from in the configuration file.
compressNot supported
named_pipeNot supported
autocommit是否自动提交,默认不自动提交,参数值为 None 表示以服务器为准
local_infileBoolean to enable the use of LOAD DATA LOCAL command. (default: False)
max_allowed_packet发送给服务器的最大数据量,默认为 16MB
defer_connect是否惰性连接,默认为立即连接
auth_plugin_mapA 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_keySHA256 authenticaiton plugin public key value. (default: None)
db参数 database 的别名
passwd参数 password 的别名
binary_prefixAdd _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》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇iOS 编译过程原理(2)Blend基础动画下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

MySQL&ES连接池

 数据库的连接池建议放在类似settings.py的配置模块中,因为基本都是配置项,方便统一管理。 1) 连接池类#settings.py import os from DBUtils.PooledDB import PooledDB from elasticsearch import Elasticsearch import pymysql class...

Scrapy 框架 入门教程

Scrapy入门教程 在本篇教程中,我已经安装好Scrapy 本篇教程中将带您完成下列任务: 创建一个Scrapy项目 定义提取的Item 编写爬取网站的 spider 并提取 Item 编写 Item Pipeline 来存储提取到的Item(即数据) 创建项目 在开始爬取之前,您必须创建一个新的Scrapy项目。 进入您打算存储代码的目录中,运行...

MXNet深度学习库简介

MXNet深度学习库简介 摘要: MXNet是一个深度学习库, 支持C++, Python, R, Scala, Julia, Matlab以及JavaScript等语言; 支持命令和符号编程; 可以运行在CPU,GPU,集群,服务器,台式机或者移动设备上. mxnet是cxxnet的下一代, cxxnet借鉴了Caffe的思想, 但是在实现上更加干净....

python第八天)——购物车作业优化完成

发现之前的三级菜单代码有BUG现已经修改过来了 购物车程序:启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表允许用户根据商品编号购买商品用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时退出,退出时,打印已购买商品和余额在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示用户下一次登录后,输...

MySQL存储过程之事务管理

  MySQL存储过程之事务管理 ACID:Atomic、Consistent、Isolated、Durable 存储程序提供了一个绝佳的机制来定义、封装和管理事务。 1,MySQL的事务支持 MySQL的事务支持不是绑定在MySQL服务器本身,而是与存储引擎相关: Java代码 1         MyISAM:不支持事务,用于只读程序提高性能 ...

python网编_进程之开启一个进程

直接上代码: importtime,os from multiprocessing importProcess # 导入模块 deffunc(): time.sleep(1) print('hello',os.getpid()) #os.getpid()的作用是打印进程id if __name__ == '__main__':...