python将字典内容存入mysql实例代码
作者:李博Garvin 时间:2024-01-22 11:23:04
本文主要研究的是python将字典内容存入mysql,分享了实现代码,具体介绍如下。
1.背景
项目需要,用python实现了将字典内容存入本地的mysql数据库。比如说有个字典dic={"a":"b","c":"d"},存入数据库效果图如下:
2.代码
'''''
Insert items into database
@author: hakuri
'''
import MySQLdb
def 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)
来源:http://blog.csdn.net/buptgshengod/article/details/36185757?utm_source=tuicool
标签:python,mysql,实例
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
微信小程序地图定位的实现方法实例
2023-08-25 10:13:10
![](https://img.aspxhome.com/file/2023/7/56187_0s.gif)
jQuery页面滚动浮动层智能定位实例代码
2024-04-22 22:22:16
61条面向对象设计的经验原则
2008-05-08 13:05:00
玩转python爬虫之URLError异常处理
2021-03-22 07:36:34
基于python生成器封装的协程类
2022-09-25 04:57:53
django模板加载静态文件的方法步骤
2023-04-12 17:13:26
解决Pytorch训练过程中loss不下降的问题
2023-03-01 09:30:22
Tornado Web服务器多进程启动的2个方法
2022-01-21 04:41:05
Vue+Django项目部署详解
2024-04-30 10:20:16
使用Python+Appuim 清理微信的方法
2021-05-24 12:22:05
![](https://img.aspxhome.com/file/2023/8/105358_0s.jpg)
详解python单例模式与metaclass
2021-03-20 23:43:56
利用python numpy+matplotlib绘制股票k线图的方法
2022-12-16 07:21:52
![](https://img.aspxhome.com/file/2023/0/67880_0s.jpg)
PDO::query讲解
2023-06-08 18:09:37
Python列出一个文件夹及其子目录的所有文件
2023-12-08 17:49:01
WebSocket部署服务器但外网无法连接的解决方法
2023-04-14 05:26:20
![](https://img.aspxhome.com/file/2023/3/127203_0s.png)
Python实现的根据文件名查找数据文件功能示例
2022-05-13 17:47:40
Python设计模式之享元模式原理与用法实例分析
2021-08-20 20:01:57
![](https://img.aspxhome.com/file/2023/1/118561_0s.png)
ASP FSO显示特殊文件夹的实现代码(畸形目录名、UNC路径)
2012-11-30 20:10:46
微信小程序-滚动消息通知的实例代码
2024-04-16 10:41:16
![](https://img.aspxhome.com/file/2023/8/136558_0s.gif)
Hive-SQL查询连续活跃登录用户思路详解
2024-01-22 08:29:47
![](https://img.aspxhome.com/file/2023/2/113552_0s.png)