David542
David542

Reputation: 110562

MySQL + Python: Not all arguments converted during string formatting

I am trying to do an INSERT into MySQL using the cursor.execute(sql, args) syntax. This is what I currently have:

# data = {...}
qmarks = ', '.join('?' * len(data))   
query = "INSERT INTO title (%s) VALUES (%s)" %(qmarks, qmarks) 
args = data.keys() + data.values()
print len(args), print len(data)
cursor.execute(query, args)

TypeError: not all arguments converted during string formatting

I checked the length of args (22) and quarks (11 x 2 = 22), and they seem to be the same. What is causing this error, and what do I need to change?

Update: When I try and do the string formatting using %s, it also throws an error:

>>> data={'provider':'asdf', 'vendor_id': '1234'}
>>> format = ', '.join(['%s'] * len(data)) 
>>> query = "INSERT INTO title (%s) VALUES (%s)" %(format, format)
>>> query
'INSERT INTO title (%s, %s) VALUES (%s, %s)'
>>> cursor.execute(query, args)
Traceback (most recent call last):
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax 
to use near ''vendor_id', 'provider') VALUES ('1234', 'asdf')' at line 1")

I think this has to do with the fact that the column definitions are strings:

INSERT INTO title ('vendor_id', 'provider') VALUES ('1234', 'asdf')

instead of:

INSERT INTO title (vendor_id, provider) VALUES ('1234', 'asdf')

Is there a way to use string formatting here but pass a variable instead of a string?

Upvotes: 1

Views: 9256

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208705

Assuming you are using MySQLdb, you want to have %s in the final query, not ?, you will also need to enter the column names directly into the query instead of using the %s replacement for them:

# data = {...}
columns = ', '.join(data.keys())
format = ', '.join(['%s'] * len(data))
query = "INSERT INTO title (%s) VALUES (%s)" % (columns, format)
cursor.execute(query, data.values())

Upvotes: 4

Related Questions