1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

If i understand you correctly, i need to add 15 %s to my query string?
I added this: 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, %s ,%s ,%s, %s, %s, %s, %s, %s, %s, %s ,%s, %s, %s, %s);' % var_string Now i get: TypeError: not enough arguments for format string
@HyperDevil: in your example code, you can omit data altogether from the execute call since you're actually inserting the values into your query string with string formatting. However, this is probably a HORRIBLE idea since this is the best way to create SQL injection vulnerabilities. Lose the string formatting and var_string and do use the 15 %ss
I used this (now(), %s, %s ,%s ,%s, %s, %s, %s, %s, %s, %s, %s ,%s, %s, %s, %s);' % data it is still complainting: TypeError: not enough arguments for format string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.