In PostgreSQL, is it possible to parameterize the table name used in a query?
1 Answer
Think of parameters as a replacement for scalar values only. Use one parameter in the place where you could use one string literal or numeric literal.
You cannot use parameters for other parts of an SQL query:
- Identifiers like table names, column names, etc.
- SQL keywords
- Expressions
- Lists of values, such as in an
IN (...)predicate. Each value in the list would need an individual parameter.
All those parts of the SQL query must be fixed by the time the query is parsed during prepare(). If a client library supports "parameters" for identifiers, it's really doing string-interpolation into the SQL query before the query is parsed.
pyscopg2does support escaping identifiers like table names.