Python stores dictionary content into mysql python
1. the background project needs to use python to store dictionary content to a local mysql database. For example, a dictionary dic = {"a": "B", "c": "d"} is saved to the database as follows:
2. code
'''Insert items into database @ author: hakuri ''' import MySQLdbdef InsertData (TableName, dic): try: conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = '*****', db = 'test', port = 3306) # connect to database cur = conn. cursor () COLstr = ''# column field ROWstr ='' # row field ColumnStyle = 'varchar (20) 'for key in dic. keys (): COLstr = COLstr + ''+ key + ColumnStyle + ', 'rowstr = (ROWstr +'" % s "'+ ',') % (dic [key]) # check whether the table exists. if try exists, execute try. if try exists, execute begin T to create a new table, and then insert try: cur.exe cute ("SELECT * FROM % s" % (TableName) cur.exe cute ("insert into % s VALUES (% s)" % (TableName, ROWstr [: -1]) except MySQLdb. error, e: cur.exe cute ("create table % s (% s)" % (TableName, COLstr [:-1]) cur.exe cute ("insert into % s VALUES (% s)" % (TableName, ROWstr [:-1]) conn. commit () cur. close () conn. close () distinct T MySQLdb. error, e: print "Mysql Error % d: % s" % (e. args [0], e. args [1]) if _ name __= = '_ main _': dic = {"a": "B", "c ": "d"} InsertData ('testtable', dic)