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)