使用psycopg2删除PostgreSQL表报跨库引用未实现错误如何解决
错误原因
PostgreSQL 对标识符的默认解析规则为「数据库名.模式名.表名」,你的表本身存储在public模式下,表名实际为subname.table(本身包含点号),直接写public.subname.table会被PostgreSQL误解析为「跨库访问public数据库下subname模式的table表」,而PostgreSQL不支持跨库引用,因此抛出该错误。
解决方案
你需要将包含特殊字符(点、空格、大小写混合等)的表名用双引号包裹,正确的删表语句为:
DROP TABLE public."subname.table";
代码优化
你当前的实现直接使用字符串拼接构造SQL,既无法处理带特殊字符的标识符,也存在SQL注入风险,推荐使用psycopg2内置的sql模块安全构造SQL,修改后的代码如下:
import os import psycopg2 from psycopg2 import sql print('Connecting to the PostgreSQL database...') postgresConnection = psycopg2.connect( host=XXXXXX, port=YYYYYYYYY, database="mydb", user=os.environ['user'], password=os.environ['pwd']) cursor = postgresConnection.cursor() # 拆分模式名和表名,这里你的模式是public,表名是subname.table schema_name = 'public' table_name = 'subname.table' # 安全构造删表语句 dropTableStmt = sql.SQL("DROP TABLE {}.{};").format( sql.Identifier(schema_name), sql.Identifier(table_name) ) print(dropTableStmt.as_string(postgresConnection)) cursor.execute(dropTableStmt) postgresConnection.commit() cursor.close() print('Database cursor closed.') postgresConnection.close() print('Database connection closed.')
如果你的name_Table参数是动态传入的固定格式(模式名.表名,表名可包含点),可以用以下方式拆分,兼容表名包含任意数量点的场景:
schema_name, table_name = name_Table.split('.', 1)
内容的提问来源于stack exchange,提问作者00__00__00
相关产品推荐
相关产品推荐

