从Python字典中插入值,包括MySQL的密钥

时间:2015-02-23 19:24:11

标签: python mysql dictionary

我有以下字典:

   {    '': ['0', '9'], 
    '3904': ['playback_error', '87'], 
    '3808': ['playback_error', '24'], 
    '3902': ['qp_library_failed_to_start', '1'], 
    '3903': ['playback_error', '464'],
     '3805': ['playback_error', '141'], 
    '3807': ['playback_error', '29'], 
    '3806': ['playback_error', '1'], 
    '1309': ['playback_error', '2'],
     '3803': ['playback_error', '28'], 
    'BL-1008': ['parental_controls_error', '5'], 
    'errorCode': ['eventKey', '2'],
     '404': ['tbr_error', '68'],
     '3308': ['playback_error', '10']}

我想将这些值插入到mysql数据库中,例如:

   ERRORCODE, EVENTKEY, COUNT

    3904, playback_error, 87

    3808,playback_error, 24

    3902,qp_library_failed_to_start,1

    3903,playback_error

我创建了一个python代码来执行此操作,但它不会将值插入数据库  我收到错误:mysql_exceptions.OperationalError:(1136,"列数不匹配第1行和第34行的值计数;) 这是我的python代码:

data=mydict
print data
#print data.values()

# Open database connection
db = MySQLdb.connect(host,user,passwd,db)

cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = '''INSERT INTO errorscode (id,date,errorcode,eventkey,count) VALUES(NULL,(DATE_ADD(CURDATE(), INTERVAL -1 day),%s,%s,%s))'''


   # Execute the SQL command
   cursor.executemany(sql,data.values())
   # Commit your changes in the database
   db.commit()

   # disconnect from server
   cursor.close()
   db.close()

感谢下面的答案,我解决了我的问题最终代码工作100%:):

#!/usr/bin/python
from StringIO import StringIO
import numpy as np
import csv
import MySQLdb
import os

with open('csv_err2.log', mode='r') as infile:
    reader = csv.reader(infile)
    mydict = dict((rows[0],[rows[2], rows[1]]) for rows in reader)

data=mydict
print data

# Open database connection
db = MySQLdb.connect(host="localhost",user="root",passwd="bravoecholimalima",db="capacityreports_mobiletv")

cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = '''INSERT INTO errorscode (id,date,errorcode,count,eventkey) VALUES(NULL,(DATE_ADD(CURDATE(), INTERVAL -1 day)),%s,$

sql_values_list = list()
for key, value in data.iteritems():
    sql_values_list.append((key,int(value[0]),value[1]))

print sql_values_list

# Execute the SQL command
cursor.executemany(sql, sql_values_list)

# Commit your changes in the database
db.commit()

# disconnect from server
cursor.close()
db.close()

1 个答案:

答案 0 :(得分:1)

嗯,这种方法不起作用。

对于其中一个,您的案例中的mydict.values()data.values()将是一个列表列表:

  

[[' 0',' 9'],[' playback_error',' 87'],[' playback_error& #39;,' 24'],   [' qp_library_failed_to_start',' 1'],[' parental_controls_error',' 5'],   [' playback_error',' 141'],[' playback_error',' 29'],   [' playback_error',' 1'],[' playback_error',' 2'],[' playback_error',   ' 28'],[' eventKey',' 2'],[' playback_error',' 10'], [' playback_error&#39 ;,   ' 464'],[' tbr_error',' 68']]

所以,如果你想迭代,你需要的东西是:

sql = '''INSERT INTO errorscode (id,date,errorcode,eventkey,count) VALUES(NULL,(DATE_ADD(CURDATE(), INTERVAL -1 day),%s,%s,%s))'''

sql_values_list = list()
for key, value in data.iteritems():
    sql_values_list.append((key, value[0], value[1]))

try:
    # Execute the SQL command
    cursor.executemany(sql, sql_values_list)
    # Commit your changes in the database
    db.commit()
except:
    # bla

data.iteritems()将在迭代期间一次性检索密钥和相应的值,您可以进一步使用。您的价值是一个列表,这就是为什么要将其传递给您,您需要明确地解决这些成员问题。

您将dict重组为.executemany()的格式并将其传递。

请注意,如果您的数据结构不是静态的,那么我在示例中显示的方式可能不安全,即如果您有一个值,其中list只包含1个元素 - 代码将失败。