Home:ALL Converter>Insert variable values to variable columns in MySql & python

Insert variable values to variable columns in MySql & python

Ask Time:2014-04-27T00:34:45         Author:user3576354

Json Formatter

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!

Author:user3576354,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/23313717/insert-variable-values-to-variable-columns-in-mysql-python
yy