Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two lists.

one a list of output strings from a sensor. eg

output = "1,2,3,4,5,6"
output = output.split (',')

the second list is the column headers

columns = "date,time,name,age,etc,etc2"
columns = columns.split (',')

the order of the columns variable changes as do the output values.

I want to upload the date to mysql using columns variable to dictate the fields and outputs variable for the values.

this is my code which does not see columns as a list only as a single value?

#!/usr/bin/python

from device import output
from device import columns

mydb = MySQLdb.connect(host="localhost", user="", passwd="", db="")
cursor = mydb.cursor()

with mydb:
    cursor.execute('INSERT INTO logging(columns) '\
         'VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', output)

error given

Traceback (most recent call last):
  File "./upload4.py", line 27, in <module>
    'VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', output)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1")

Any help appreciated!

share|improve this question
2  
You are using more values than second argument (output) can provide –  frostnational Apr 26 at 16:42
add comment

1 Answer

The query should be built in this way:

'INSERT INTO logging({}) VALUES({})'.format(','.join(columns), ','.join(['%s'] * len(columns)))

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.