說明:
以下例子是批量插入三條數據,需要插入多少,可以自己定義
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()