Psycopg2传递表名至查询执行失败,误识别为列名求解决
问题原因与解决方案
为什么传表名会被识别为列名?
你在查询information_schema.columns时,错误地用了sql.Identifier来传递表名字符串。sql.Identifier的作用是生成带双引号的数据库对象标识符(比如列名、表名这类对象),所以当你把它放在table_name = {}的位置时,生成的SQL会变成:
SELECT column_name FROM information_schema.columns WHERE table_name = "table1";
在PostgreSQL里,双引号包裹的内容会被解析成列名或表名,而不是字符串值。数据库自然会认为你要找名为table1的列,于是抛出column "xxx" does not exist的错误。
反观你在UPDATE语句中用sql.Identifier(col_name)是完全正确的——因为那里确实需要引用列名这个数据库对象标识符。
修复代码的两种方式
方式1:用sql.Literal传递字符串值
把sql.Identifier换成sql.Literal,它会正确生成字符串字面量:
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.Literal('table1'))) columns = cur.fetchall() except Exception as e: print(f"Error: {e}")
方式2:直接用参数化查询(更推荐)
psycopg2支持直接用占位符传递参数,这种方式更简洁且能更好地避免SQL注入:
try: q = "SELECT column_name FROM information_schema.columns WHERE table_name = %s;" cur.execute(q, ('table1',)) columns = cur.fetchall() except Exception as e: print(f"Error: {e}")
内容的提问来源于stack exchange,提问作者tab_philomath
相关产品推荐
相关产品推荐

