PHP笔记网

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2020-12-11 23:05:12  修改时间:2024-11-30 04:42:21  分类:10.Python基础  编辑

使用pymysql的 course.executemany(sql, update_list) 进行批量更新

  • sql:更新一条的sql语句模板;
  • update_list:一个列表套元组的结构;

示例:

db = pymysql.connect(user='root', password='mysql', database='test', host='127.0.0.1', port=3306, charset='utf8mb4')

name_list = ["re", "gh", "ds", "D"]  # 存储name的值
age_list = ["10", "20", "30", "40"]  # 存储age的值
id_list = ["1", "2", "3", "4"]  # 存储id的值
val_list = [[name_list[i], age_list[i], id_list[i]] for i in range(len(id_list))]
print(val_list)
# [['re', '10', '1'], ['gh', '20', '2'], ['ds', '30', '3'], ['D', '40', '4']]

with db.cursor() as cursor:
    try:
        sql = "UPDATE test SET name=(%s), age=(%s) WHERE id=(%s)"
        cursor.executemany(sql, val_list)
        db.commit()
    except:
        db.rollback()
db.close()

 

 

相关文章

  1. (Python)批量更新MySQL 42万条数据
  2. MySQL的批量修改数据
  3. Python操作MySQL批量插入数据:cursor.executemany()