1. BackgroundThe project needs to use Python to save the dictionary contents to the local MySQL database. For example, there is a dictionary dic={"a": "B", "C": "D"}, stored in the database as follows:
2. Code
' Insert items into Database@author:hakuri ' ' Import mysqldbdef insertdata (tablename,dic): Try:conn=mysqldb.conn ECT (host= ' localhost ', user= ' root ', passwd= ' * * * *, db= ' test ', port=3306) #链接数据库 cur=conn.cursor () colstr= ' #列的字段 R Owstr= ' #行字段 columnstyle= ' VARCHAR ' for key in Dic.keys (): colstr=colstr+ ' +key+columnstyle+ ', ' Rowstr= (rowstr+ ' "%s" ' + ', ')% (Dic[key]) #判断表是否存在, there is a execute try, there is no execution except new table, and then insert Try:cur.execute ("Sele CT * from%s "% (TableName)) Cur.execute (" INSERT into%s VALUES (%s) "% (tablename,rowstr[:-1)) except MySQLdb . Error,e:cur.execute ("CREATE TABLE%s (%s)"% (Tablename,colstr[:-1])) Cur.execute ("INSERT into%s VA Lues (%s) "% (Tablename,rowstr[:-1])) Conn.commit () Cur.close () conn.close () except Mysqldb.error,e:print" Mysql Error%d:%s "% (E.args[0], e.args[1]) if __name__== ' __main__ ': dic={" a ":" B "," C ":" D "} insertdata (' Testt Able ', DIC)