网站首页 > 文章精选 正文
一、应用场景
上篇文章我们学会了在pymysql事务中批量插入数据的复用代码,既然有了批量插入,那批量更新和批量删除的操作也少不了。
二、解决思路
为了解决批量删除和批量更新的问题,提出如下思路:
- 所有更新语句的生成都共用一个入口
- 更新的数据库字段和参数可动态决定
- 要操作的表名可动态决定
- 返回where条件前的sql语句
三、解决办法
- 这里只演示批量更新的解决办法,批量删除的类似。
- 跟插入语句不同的是,更新语句的where条件前set的数据才可以进行动态生成sql语句,而where条件后面的需要另外拼接。
- 例如:
update user_info set name ='头条号_code_space',size='30cm' where id=1
其中where条件前的sql就是我们要进行动态sql拼接的,通用方法此时只返回where条件前的sql语句。
def common_update_sql(item, table):
"""
从item的key-value提取要更新的字段,进行更新
:param item: 要执行更新的字段的字典,{"colunm_name_1":"colunm_value_1","colunm_name_2":"colunm_value_2"}
:param table: 数据库表名
:return: 返回拼接好的where条件前的sql更新语句
"""
update = ','.join([" {key} = %s".format(key=key) for key in item])
update_sql = 'update {table} set '.format(table=table) + update
return update_sql
四、测试demo
# -*- coding: utf-8 -*-
"""
@Time : 2022/1/29 12:50
@Auth : 技术空间
@File :handle_list_sql_demo2.py
@IDE :PyCharm
@Motto:技术总是要日积月累的
"""
import pymysql
def common_update_sql(item, table):
"""
从item的key-value提取要更新的字段,进行更新
:param item: 要执行更新的字段的字典,{"colunm_name_1":"colunm_value_1","colunm_name_2":"colunm_value_2"}
:param table: 数据库表名
:return: 返回拼接好的where条件前的sql更新语句
"""
update = ','.join([" {key} = %s".format(key=key) for key in item])
update_sql = 'update {table} set '.format(table=table) + update
return update_sql
def select_list(db_cursor, sql):
"""
查询数据量表的列表
:param db_cursor: 游标
:param sql: 拼接好的sql查询语句
:return: 返回查询结果列表
"""
db_cursor.execute(sql)
data_list = db_cursor.fetchall()
print(data_list)
return data_list
if __name__ == '__main__':
db = pymysql.connect(host='localhost',
user='root',
password='root',
database='others')
cursor = db.cursor(pymysql.cursors.DictCursor)
table_1 = "user_info"
table_2 = "user_role"
select_user_sql = " select id,name from " + table_1
select_role_sql = " select user_id,role_id from " + table_2
try:
print("执行批量更新user前的数据-->")
select_list(cursor, select_user_sql)
update_user_list = []
for i in range(4, 7):
update_user_list.append({"name": "头条号_code_space_" + str(i)})
# 更新user表的id为4,5,6的数据
for i in range(3):
update = update_user_list[i]
update_sql = common_update_sql(update, table_1)
update_sql = update_sql + " where id=" + str(i + 4)
cursor.execute(update_sql, tuple(update.values()))
# 开始批量插入表2
print("执行批量更新user_role前的数据-->")
select_list(cursor, select_role_sql)
update_role_list = []
for i in range(4, 7):
update_role_list.append({"user_id": i, "role_id": 2})
# 更新user_role表的id为4,5,6的数据
for i in range(3):
update = update_role_list[i]
update_sql = common_update_sql(update, table_2)
update_sql = update_sql + " where id=" + str(i + 4)
cursor.execute(update_sql, tuple(update.values()))
except Exception as e:
# 事务回滚
db.rollback()
print('事务处理失败', e)
else:
# 事务提交
db.commit()
print('事务处理成功', cursor.rowcount)
print("执行批量更新user后的数据-->")
select_list(cursor, select_user_sql)
print("执行批量更新user_role后的数据-->")
select_list(cursor, select_role_sql)
cursor.close()
db.close()
关注我,坚持每日积累一个技巧,长期坚持,我们将会不断进步。
- 上一篇: pytest框架进阶自学系列 | 常用插件的使用
- 下一篇: 智能代码助手【文心快码】你了解吗?
猜你喜欢
- 2024-12-23 python网络爬虫:批量爬取图片 python批量爬取图片并保存
- 2024-12-23 10w qps缓存数据库——Redis redis缓存数据量多大开始性能下降
- 2024-12-23 Python File(文件) 常用场景 python中file.write
- 2024-12-23 「JS 逆向百例」某网站加速乐 Cookie 混淆逆向详解
- 2024-12-23 「JS 逆向百例」猿人学web比赛第五题:js 混淆 - 乱码增强,详细剖析
- 2024-12-23 Python 操作mysql实现事务处理 python+操作mysql实现事务处理功能
- 2024-12-23 python 大量乱序文件如何合并成有序的
- 2024-12-23 如何使用 PyScript 在 Web 浏览器上轻松运行
- 2024-12-23 Selenium4.0+Python3系列(四) - 常见元素操作(含鼠标键盘事件)
- 2024-12-23 Selenium4+Python3系列(六) - 强制等待、隐式等待、显式等待
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 稳压管的稳压区是工作在什么区 (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)