Skip to main content
 首页 » 编程设计

python之psycopg2 传入表名

2024年10月24日16JustinYoung

我有以下查询

table = "#temp_table" 
cursor.execute("""select * from %s as a """, (table)) 

我不断收到来自语句的语法错误。为什么这行不通?

请您参考如下方法:

您收到此错误是因为传递到第二个参数 (table)(实际上应该是 (table,))的参数在 SQL 中被转义了运行的语句。

在此示例中,select * from %s as a 被转换为 select * from '#temp_table' as a,这是一个错误。要正确插入表名,需要直接格式化 SQL 语句字符串,如下所示:

query = 'select * from "{}" as a'.format(table) 
cursor.execute(query) 

您应该非常小心以这种方式将哪些数据插入到查询中,因为它极易受到 SQL 注入(inject)攻击。不要将其用于不受信任的数据。