Home > Database > Mysql Tutorial > How Can I Safely Pass Table Names as Parameters in Psycopg2?

How Can I Safely Pass Table Names as Parameters in Psycopg2?

Patricia Arquette
Release: 2025-01-12 11:07:43
Original
571 people have browsed it

How Can I Safely Pass Table Names as Parameters in Psycopg2?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template