我有一个庞大的列表(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()但是没有success..any的帮助?
发布于 2013-05-04 04:15:07
我想知道在你的逻辑中,这一行注释是否正确?
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)。
https://stackoverflow.com/questions/15817634
复制相似问题