Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to dump Python dictionary (dict) object to a MySQL table?

I have a dict object. I dumped the data using this:

for alldata in data: # print all data to screen
    print data[alldata]

Each field had brackets [] and 'None' values for NULLS and date.datetime for date values.

How do I dump this dict to MySQL table? Thank you!

print data displays something like this :

{'1': ['1', 'K', abc, 'xyz', None, None, None], '2': ['2', 'K', efg, 'xyz', None, None, None], '3': ['3', 'K', ijk, 'xyz', None, None, None]}

How to insert this data into MySQL?

like image 523
ThinkCode Avatar asked Apr 09 '10 22:04

ThinkCode


People also ask

Is dictionary in Python fast?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.

Can you store a dictionary in mysql?

The data dictionary schema stores dictionary data in transactional ( InnoDB ) tables. Data dictionary tables are located in the mysql database together with non-data dictionary system tables. Data dictionary tables are created in a single InnoDB tablespace named mysql. ibd , which resides in the MySQL data directory.

Which method can be used to take a value out of a dictionary?

To delete a key, value pair in a dictionary, you can use the del method.


2 Answers

Assuming you have MySQLdb (mysql-python) installed:

sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}

conn = MySQLdb.connect(**params)

cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()

conn.close()
like image 149
newtover Avatar answered Oct 12 '22 22:10

newtover


this one is giving a very nice example and more compatible one. http://code.activestate.com/recipes/457661-generate-sql-for-insertation-into-table-from-dicti/

like image 42
Azamat Tokhtaev Avatar answered Oct 12 '22 23:10

Azamat Tokhtaev