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()
转义特殊字符
connection.escape_string(str)
参数化语句
支持传入参数进行自动转义、格式化 SQL 语句,以避免 SQL 注入等安全问题。
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx