I have the following 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']}
I want to insert those values into mysql database for example:
ERRORCODE, EVENTKEY, COUNT
3904, playback_error, 87
3808,playback_error, 24
3902,qp_library_failed_to_start,1
3903,playback_error
I created a python code to perform this action but it doesnt insert the values to the database i get the error : mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1") here's my python code:
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()
Thanks to an answer below, i fix my problems FINAL CODE WORKING 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()
exceptwith a rollback.raisestatement immediately after thedb.rollback(), then you'll at least see the exception and maybe have a place to start debugging.