psycopg2 TypeError: not all arguments converted during string formatting

两盒软妹~` 提交于 2019-11-29 18:03:28

问题


I'm trying execute a simple query, but getting this error no matter how I pass the parameters.

Here is the query (I'm using Trac db object to connect to a DB):

cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))

schema and each['id'] both are simple strings

print("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))

Result: SELECT name FROM "Planing".customer WHERE firm_id='135'

There is on error is a remove quote after firm_id=, but that way parameter is treated a an integer and ::text leads to the very same error.


回答1:


You shouldn't use string interpolation for passing variables in database queries, but using string interpolation to set the table name is fine (as long as it's either not an external input or you restrict the allowed value). Try:

cursor.execute("""SELECT name FROM %s.customer WHERE firm_id=%%s""" % schema, each['id'])

Rules for DB API usage provides guidance for programming against the database.




回答2:


In my case I didn't realize that you had to pass a tuple to cursor.execute. I had this:

cursor.execute(query, (id))

But I needed to pass a tuple instead

cursor.execute(query, (id,))



回答3:


I got this same error and couldn't for the life of me work out how to fix, in the end it was my stupid mistake because I didn't have enough parameters matching the number of elements in the tuple:

con.execute("INSERT INTO table VALUES (%s,%s,%s,%s,%s)",(1,2,3,4,5,6))

Note that I have 5 elements in the values to be inserted into the table, but 6 in the tuple.




回答4:


The correct way to pass variables in a SQL command is using the second argument of the execute() method. And i think you should remove single quotes from second parameter, read about it here - http://initd.org/psycopg/docs/usage.html#the-problem-with-the-query-parameters.

Note that you cant pass table name as parameter to execute and it considered as bad practice but there is some workarounds:
Passing table name as a parameter in psycopg2
psycopg2 cursor.execute() with SQL query parameter causes syntax error

To pass table name try this:

cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id=%s""" % (schema, '%s'), (each['id'],))



回答5:


Use AsIs

from psycopg2.extensions import AsIs

cursor.execute("""
    select name 
    from %s.customer 
    where firm_id = %s
    """, 
    (AsIs(schema), each['id'])
)


来源:https://stackoverflow.com/questions/21524482/psycopg2-typeerror-not-all-arguments-converted-during-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!