gpt4 book ai didi

python - psycopg2 传入表名

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:45 27 4
gpt4 key购买 nike

我有以下查询

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)攻击。不要将其用于不受信任的数据。

关于python - psycopg2 传入表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32315486/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com