HyperDevil
HyperDevil

Reputation: 2649

Python MySQL insert with list

I am trying to insert data into MySQL with a list using Python.
The list contains both strings and integers.
I am not able to use %s for string replacement also % does not work.

def insert(self,data):
    db =  MySQLdb.connect(db=self.database,host=self.host,port=self.port,user=self.user,passwd=self.password)
    c=db.cursor()
    var_string = ', '.join('?' * len(data))
    query = 'INSERT INTO wmr200 (time, temp_in, temp_out, dewpoint, hum_in, hum_out, windspeed, wind_direction, windchill, rain_1h, rain_24h, rain_total, rel_pressure, abs_pressure, tendency, forecast) VALUES (now(), %s);' % var_string
    c.execute(query, data)

error is:

File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

Upvotes: 1

Views: 2076

Answers (1)

NPE
NPE

Reputation: 500923

The expression that produces the exception:

query % db.literal(args)

requires query to contain one format string -- such as %s -- per each element of db.literal(args).

Yet the value of query as produced by your function contains exactly zero format strings.

Upvotes: 2

Related Questions