Python MySQLdb 批量插入 封装
2024-08-24 03:52:01
def insert_data_many(dbName,list_data_dict):
try:
# 得到列表的第一个字典集合
data_dict = list_data_dict[0]
# 得到(s%,s%,s%,s%)
data_values = "(" + "%s," * (len(data_dict)) + ")"
data_values = data_values.replace(',)', ')') dbField = data_dict.keys()
dataTuple = tuple(data_dict.values())
dbField = str(tuple(dbField)).replace("'",'')
conn = MySQLdb.connect(host="xxxxxxx", user="xxxx", passwd="xxxxxx", db="xxxxxx", charset="utf8")
cursor = conn.cursor() sql = """ insert into %s %s values %s """ % (dbName,dbField,data_values) params = []
for item in list_data_dict:
params.append(tuple(item.values()))
params = tuple(params) cursor.executemany(sql, params)
conn.commit()
cursor.close() print "===== 插入成功 ====="
return 1 except Exception as e:
print "******** 插入失败 ********"
print e
return 0
使用说明:
data2 = { "sold_price":str(sold_price),
"estimate_price":str(estimate_price),
"item_url":str(item_url),
"item_imgurl":str(item_imgurl),
"item_lotnum":str(item_lotnum), "hashcode": hashcode,
"create_time": create_time,
} data_list.append(data_dict)
dbName = "oversea_thierrydemaigret_2017_2_no_detail_info" # 其中 data_list 的数据格式是: [{},{},{},{},{},{},{}] result1 = insert_data_many(dbName, data_list)
最新文章
- C#学习笔记----.net操作进程
- python利用xmlrpc方式对odoo数据表进行增删改查操作
- @synchronized (object)使用详解
- C#学习笔记三: C#2.0泛型 可控类型 匿名方法和迭代器
- Checkbox 全选、反选
- poj 3190 Stall Reservations 贪心 + 优先队列
- MySQL中函数、游标、事件、视图基本应用举例(代码)
- DailyTick 开发实录 —— UI 设计
- Struts2第十篇【数据校验、代码方式、XML配置方式、错误信息返回样式】
- TPYBoard实例之利用WHID为隔离主机建立隐秘通道
- C#基础知识之属性
- OpenLayers加载谷歌地图服务
- 《Python》 面向对象初识
- 从exp入手分析漏洞
- 希尔排序之C++实现(高级版)
- (Nginx) URL REWRITE
- Java Log Viewer日志查看器
- 浏览器根对象window之performance
- Outlets 和Referencing Outlets的区别
- git代码提交与克隆