说明:
以下例子是批量插入三条数据,需要插入多少,可以自己定义
dbinfo = {
"host": "192.168.90.0",
"user": "root",
"password": "XXX",
"port": 3306,
}
name_list = ["hi", "hello", "hey"]
address_list = ["10", "20", "30"]
mobile_list = ["10", "20", "30"]
val_list = [[name_list[i], address_list[i], mobile_list[i]] for i in range(len(name_list))]
print(val_list)
ins_sql = "INSERT INTO {}(name,address,mobile)VALUES ({}, {},{});"
sql = ins_sql.format(table_name,'%s','%s','%s')
cursor = dbinfo.cursor()
cursor.executemany(sql,val_list)
db.commit()
需要进行批量插入的字段:
[[name_list[i], address_list[i], mobile_list[i]] for i in range(len(name_list))]
有三个字段,分别是:
name_list、address_list、mobile_list
从这三个字段中取每个下标值
name_list[i], address_list[i], mobile_list[i]
在这个区间下进行循环:
len(name_list)
执行sql:
INSERT INTO {}(name,address,mobile)VALUES ({}, {},{});
连接数据库执行语句,提交:
cursor.executemany(sql,val_list)
db.commit()