简体   繁体   English

在MySQL中插入列表的Python列表

[英]Insert a Python list of lists in MySQL

I have a huge list (A) comprising of multiple sub lists (x, y, ... n), with each sub-list containing ['a', 'b', 'c', 'd', 'e', 'f', 'g'] elements. 我有一个庞大的列表(A),由多个子列表(x,y,... n)组成,每个子列表都包含['a','b','c','d','e' ,'f','g']元素。 I want to transfer all the content of all the sub lists to a db table (using MySQLdb module) but not able to figure out how to achieve this. 我想将所有子列表的所有内容传输到db表(使用MySQLdb模块),但无法弄清楚如何实现此目的。 What I am doing right now is like this: 我现在正在做的事情是这样的:

 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()

But having no success..any help? 但是没有成功..有什么帮助吗?

I wonder if the line comment out is correct in your logic? 我想知道该行注释在您的逻辑中是否正确?

 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))

You are more likely to do like this: 您更有可能这样做:

 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()

Use %s in executemany will let the MySQLdb do the dirty work(escape string to 'string', but keep int as int, etc. For example "str" -> "'str'", "1" -> 1). 在executemany中使用%s将使MySQLdb进行肮脏的工作(将字符串转义为'string',但将int保留为int等,例如“ str”->“'str'”,“ 1”-> 1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM