简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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