def insert_data(dbName,data_dict): try: 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="xxxxxxxxxx", user="xxxxxx", passwd="xxxxxx", db="xxxxxxx", charset="utf8") cursor = conn.cursor() sql = """ insert into %s %s values %s """ % (dbName,dbField,data_values) params = dataTuple cursor.execute(sql, params) conn.commit() cursor.close() print "===== 插入成功 =====" return 1 except Exception as e: print "******** 插入失败 ********" print e return 0
使用说明:
# 数据库的名称
dbName = "oversea_thierrydemaigret_2017_2_zc"
# 插入的数据
data_dict = { "session_url": session_url, "session_address": session_address, "hashcode": hashcode, "create_time": create_time, "session_name": session_name, "item_auct_time": item_auct_time, }
result11 = insert_data(dbName, data_dict)
print result11