Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert list of dict into MySQL using Python [closed]

Tags:

python

mysql

I want to insert a list like that ,but much larger. list=[{"name":"Tom","gender":"male",},{"name":"Jack","gender":"male",},{"name":"Lee","gender":"male",}] into MySQL using python,to build a table. I have already import MySQLdb .What should I do then?

like image 338
GUOJINGWEI Avatar asked Apr 08 '16 04:04

GUOJINGWEI


1 Answers

Assuming you have a table named foo with name and gender columns, here is how you can use executemany() to insert this list of dictionary into the table:

import MySQLdb

db = MySQLdb.connect(...)
cursor = db.cursor()

data = [
    {"name":"Tom", "gender":"male"},
    {"name":"Jack", "gender":"male"},
    {"name":"Lee", "gender":"male"}
]
cursor.executemany("""
    INSERT INTO foo (name, gender)
    VALUES (%(name)s, %(gender)s)""", data)
db.commit() 
like image 72
alecxe Avatar answered Sep 27 '22 19:09

alecxe