我有一个巨大的列表(A),包含多个子列表(x,y,... n),每个子列表包含['a','b','c','d', 'e','f','g']元素。我想将所有子列表的所有内容传输到db表(使用MySQLdb模块),但无法弄清楚如何实现这一点。我现在正在做的是这样的:
import MySQLdb
db = MySQLdb.connect("localhost","root","","test")
cursor = db.cursor()
for u in A:
for x1,x2,x3,x4,x5,x6,x7,x8 in u:
cursor.execute("INSERT INTO logs(date, time, pri, method, action, client, unknown1, unknown2) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s')" % (x1, x2, x3, x4, x5, x6, x7, x8))
db.commit()
db.close()
但没有成功......有什么帮助?
答案 0 :(得分:0)
我想知道你的逻辑中的行注释是否正确?
for u in A:
#for x1,x2,x3,x4,x5,x6,x7,x8 in u:
cursor.execute("INSERT INTO logs(date, time, pri, method, action, client, unknown1, unknown2) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s')" % (x1, x2, x3, x4, x5, x6, x7, x8))
你更有可能这样做:
import MySQLdb
db = MySQLdb.connect("localhost","root","","test")
cursor = db.cursor()
cursor.executemany("INSERT INTO logs(date, time, pri, method, action, client, unknown1, unknown2) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", A)
db.commit()
db.close()
在executemany中使用%s 将让MySQLdb执行脏工作(将字符串转义为'string',但将int保留为int等等。例如“str” - >“'str '“,”1“ - > 1)。