Safely pass table name as argument in Psycopg2
In psycopg2, it is strongly discouraged to use string concatenation ('select %s from %s where...') to pass the table name as a parameter, as it poses a security risk. Instead, consider using the safer psycopg2.sql module.
The sql module added in psycopg2 version 2.7 provides a way to dynamically generate SQL queries when selecting table names dynamically. Here's an example:
<code class="language-python">from psycopg2 import sql cur.execute( sql.SQL("insert into {table} values (%s, %s)").format(table=sql.Identifier('my_table')), [10, 20] )</code>
To represent table or field names, please use Identifier
instead of AsIs
. For security reasons, avoid using Python string concatenation or string argument interpolation.
The above is the detailed content of How Can I Safely Pass Table Names as Parameters in Psycopg2?. For more information, please follow other related articles on the PHP Chinese website!