Python pymysql 批量插入与批量更新数据库

实际上批量执行的方法也适用于单条执行,只要二维里列表中只有一个一维列表即可

批量插入到mysql

# 批量插入可以先将数据组织为二维列表,其中每一行为一条记录。比如有student表字段为:stu_id, stu_name, stu_score

# 准备数据
insert_data = [
		[1, '张三', 84],
		[2, '李四', 92],
		[3, '王五', 75]
	]

# 连接数据库
host = '127.0.0.1'  # 地址
user = 'root'  # 用户名
pwd = 'root'  # 密码
database = 'school'  # 数据库名

conn = pymysql.connect(host=host,
                       user=user, password=pwd,
                       database=database, charset='utf8')
cursor = conn.cursor()

# sql语句
sql = 'INSERT INTO student(stu_id, stu_name, stu_score) VALUES (%s, %s, %s)'

# 批量插入
try:
    res = cursor.executemany(sql, insert_data)
    print(res)
    conn.commit()
except Exception as e:
    print(e)
    conn.rollback()
finally:
    conn.close()

批量更新到mysql

# 批量更新可以先将数据组织为二维列表,其中每一行为一条更新语句需要的字段值。比如有student表,根据stu_id更新stu_score

# 准备数据
update_data = [
		[81, 1],
		[90, 2],
		[72, 3]
	]

# 连接数据库
host = '127.0.0.1'  # 地址
user = 'root'  # 用户名
pwd = 'root'  # 密码
database = 'school'  # 数据库名

conn = pymysql.connect(host=host,
                       user=user, password=pwd,
                       database=database, charset='utf8')
cursor = conn.cursor()

# sql语句
sql = 'UPDATE student SET stu_score = (%s) WHERE student_id = (%s)'

# 批量更新
try:
    res = cursor.executemany(sql, update_data)
    print(res)
    conn.commit()
except Exception as e:
    print(e)
    conn.rollback()
finally:
    conn.close()

你可能感兴趣的:(python,数据库,python,mysql,pymysql)