psycopg2 TypeError: not all arguments converted during string formatting

前端 未结 5 2032
[愿得一人]
[愿得一人] 2020-12-15 17:37

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):

相关标签:
5条回答
  • 2020-12-15 17:47

    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,))
    
    0 讨论(0)
  • 2020-12-15 17:48

    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'],))
    
    0 讨论(0)
  • 2020-12-15 17:58

    I got this same error and couldn't for the life of me work out how to fix, in the end it was my 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.

    0 讨论(0)
  • 2020-12-15 18:03

    You should not 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 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.

    0 讨论(0)
  • 2020-12-15 18:04

    Use AsIs

    from psycopg2.extensions import AsIs
    
    cursor.execute("""
        select name 
        from %s.customer 
        where firm_id = %s
        """, 
        (AsIs(schema), each['id'])
    )
    
    0 讨论(0)
提交回复
热议问题