Python操作MySQL批量更新语句

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

name_lit = ["re", "gh", "ds", "D"]  # 存储name的值
age_lit = ["10", "20", "30", "40"] # 存储age的值
id_lit = ["1", "2", "3", "4"]  # 存储id的值
lit = [[name_lit[i],age_lit[i],id_lit[i]] for i in range(len(id_lit))]
print(lit)

with connection.cursor() as cursor:
    try:
        sql = "update test SET name=(%s), age=(%s) where id=(%s)"
        cursor.executemany(sql, id_lit)
        connection.commit()
    except:
        connection.rollback()
connection.close()
发布了19 篇原创文章 · 获赞 19 · 访问量 6136

猜你喜欢

转载自blog.csdn.net/Lmingtian_huigenghao/article/details/104576850