您好,欢迎来到纯果粒美食网。
搜索
您的当前位置:首页python将字典内容存入mysql_MySQL

python将字典内容存入mysql_MySQL

来源:纯果粒美食网
 python

1.背景

项目需要,用python实现了将字典内容存入本地的mysql数据库。比如说有个字典dic={"a":"b","c":"d"},存入数据库效果图如下:

2.代码

'''Insert items into database@author: hakuri'''import MySQLdbdef InsertData(TableName,dic): try: conn=MySQLdb.connect(host='localhost',user='root',passwd='****',db='test',port=3306) #链接数据库 cur=conn.cursor() COLstr='' #列的字段 ROWstr='' #行字段 ColumnStyle=' VARCHAR(20)' for key in dic.keys(): COLstr=COLstr+' '+key+ColumnStyle+',' ROWstr=(ROWstr+'"%s"'+',')%(dic[key]) #判断表是否存在,存在执行try,不存在执行except新建表,再insert try: cur.execute("SELECT * 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 VALUES (%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('testtable',dic) 

Copyright © 2019- chunguoli.com 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务