Psycopg2 未执行将表名传递给查询

Psycopg2 is not executing the passing of a table name to query

提问人:tab_philomath 提问时间:7/18/2023 最后编辑:tab_philomath 更新时间:7/18/2023 访问量:33

问:

我不知道出了什么问题。我能够使用相同的格式传递要删除的列的名称,但是当我尝试传递表名时,它不起作用。

错误为:psycopg2.errors.UndefinedColumn:列“delete_9”不存在。

try: 
    #pass the table name to get the columns
    q = sql.SQL("SELECT column_name FROM information_schema.columns WHERE table_name = {};")
    cur.execute(q.format(sql.Identifier('table1')))
    columns = cur.fetchall()
                
except:
    print("does not pass the string table")

但这确实有效:

for i in range(len(columns)):
    col_name= columns[i][0]
  
    query = sql.SQL( "UPDATE table1 SET {} = NULL WHERE {} = X;")
   
    cur.execute(query.format(sql.Identifier(col_name),sql.Identifier(col_name)))

我正在传递一个表名来获取列。为什么它认为我在输入列?

python 字符串 参数传递 psycopg2 psql

评论

1赞 mipadi 7/18/2023
如果打印异常而不是仅吞下它,则错误消息和堆栈跟踪可能会帮助您诊断问题。
0赞 tab_philomath 7/18/2023
错误说: 回溯(最近一次调用最后一次):文件“C:\Users\stars\AppData\Local\Temp\ipykernel_18680\1389549302.py”,第 22 行,<单元格行:19> cur.execute(q.format(sql.Identifier('delete_9'))) psycopg2.errors.UndefinedColumn: 列 “delete_9” 不存在 第 1 行: ...ROM information_schema.columns 其中 table_name = “delete_9”...这没有意义,因为delete_9是表名而不是列?
0赞 mipadi 7/18/2023
我认为问题在于 ,它用于标识符,例如 中的表名,例如 .但在这里你实际上想要一个字符串,因为我相信 in 中的列包含字符串。所以你想要这样的东西,我想。sql.IdentifierSELECT * FROM {}table_nameinformation_schema.columnscur.execute("SELECT column_name FROM information_schema.columns WHERE table_name = %s;", "table1")
0赞 Adrian Klaver 7/19/2023
in 是数据值而不是标识符,因此您需要将其更改为每个传递参数{}... table_name = {}%s

答: 暂无答案