psycopg2 TypeError: not all arguments converted during string formatting
psycopg2, python, trac
Solution
It is recommended to 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.
Problem
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.
Related problems
- Passing table name as a parameter in psycopg2
- Python: best practice and securest way to connect to MySQL and execute queries
- Why does psycopg2 cursor.execute() with SQL query parameter cause syntax error?
- Why do I get "TypeError: not all arguments converted during string formatting" when trying to use a string in a parameterized SQL query?
- How to use variables in SQL statement in Python?