You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PGAdmin4及psycopg2中引用含空格的Schema名称?

PostgreSQL含空格Schema的正确引用方法

我正在编写Python脚本,通过psycopg2从PostgreSQL(PGAdmin4管理)获取数据,数据库连接无异常,但查询含空格的Schema时总是提示Schema不存在。访问无空格的Schema一切正常,以下是执行SQL查询的代码片段:

cursor = connection.cursor()
# query to retrieve from table
CD_Retrieve = "select * from Schema Name" # something wrong with this

# executes query
cursor.execute(CD_Retrieve) 

print("Selecting rows from Schema Name")
CD_Records = cursor.fetchall()

# for loop to display all records
for row in CD_Records:
    print(row[0])

我曾在PGAdmin4的查询工具中尝试用[]、{}、''、 (反引号)等符号包裹Schema名称,但仍提示Schema不存在,请问如何正确引用含空格的Schema名称?


核心解决方案:用*双引号("")*包裹含空格的标识符

PostgreSQL规定,包含空格、特殊字符或大小写敏感的标识符(Schema、表、列名等),必须用*双引号("")*包裹,这是SQL标准的标识符引用方式,其他符号(如反引号、方括号)是其他数据库(如MySQL、SQL Server)的语法,PostgreSQL不支持。

1. 在PGAdmin4查询工具中的写法

直接用双引号包裹Schema名称即可,例如:

SELECT * FROM "Schema Name";
-- 如果要查询该Schema下的表,格式为:
SELECT * FROM "Schema Name"."Table Name";

2. 在Python psycopg2中的写法

修改你的SQL语句,用双引号包裹含空格的Schema名称,注意Python字符串的引号转义(可以用单引号包裹SQL语句,内部用双引号):

cursor = connection.cursor()
# 正确引用含空格的Schema
CD_Retrieve = 'select * from "Schema Name"'

cursor.execute(CD_Retrieve) 
print("Selecting rows from Schema Name")
CD_Records = cursor.fetchall()

for row in CD_Records:
    print(row[0])

注意事项

  • 双引号包裹的标识符是大小写敏感的:如果你创建Schema时用的是"Schema Name"(首字母大写+空格),查询时必须严格对应大小写,不能写成"schema name"。
  • 避免直接拼接字符串:如果Schema名称是动态生成的,不要直接拼接SQL语句,建议使用psycopg2的quote_ident方法来安全转义标识符:
    from psycopg2.extensions import quote_ident
    
    schema_name = "Schema Name"
    # 安全转义标识符
    quoted_schema = quote_ident(schema_name, connection)
    CD_Retrieve = f'select * from {quoted_schema}'
    cursor.execute(CD_Retrieve)
    

内容的提问来源于stack exchange,提问作者KianL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:45:49