作为字典传递的命名参数:语法错误:“%”处或附近的语法错误或语法错误:类型修饰符必须是简单常量或标识符

问题描述 投票:0回答:1

在尝试使用 psycopg 执行带有参数字典的 PostgreSQL

CREATE TABLE
查询时遇到一些麻烦:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  1 09:32:32 2024

@author: me
"""

import psycopg

pg_uri = "postgres://postgres:******@localhost:5432/mydatabase"
conn_dict = psycopg.conninfo.conninfo_to_dict(pg_uri)
conn = psycopg.connect(**conn_dict)
curs = conn.cursor()

d = {"CRS": 4326}
raw = "CREATE TABLE foo (id INT, geom geometry('Point',%(CRS)s));"

query0 = psycopg.sql.SQL(raw).format(**d)
query1 = psycopg.sql.SQL(raw.format(**d))
query2 = psycopg.sql.SQL(raw)

curs.execute(query0) # SyntaxError: syntax error at or near "%"
curs.execute(query1) # SyntaxError: syntax error at or near "%"
curs.execute(query2,d) # SyntaxError: type modifiers must be simple constants or identifiers

curs.execute()
跟注任一加注:

  • SyntaxError: syntax error at or near "%"
    两个第一查询或:
  • SyntaxError: type modifiers must be simple constants or identifiers
    最后一张

相关文件

https://www.psycopg.org/psycopg3/docs/basic/params.html

版本信息

Python:3.10
心理:3.2.3
PostgreSQL:16

python postgresql psycopg2 psycopg3
1个回答
0
投票

正如

SQL.format
的文档所述,
SQL.format
使用与
str.format
相同的占位符语法,即
{CRS}
而不是
%(CRS)s

d = {"CRS": 4326}
raw = "CREATE TABLE foo (id INT, geom geometry('Point',{CRS}));"

query0 = psycopg.sql.SQL(raw).format(**d)
© www.soinside.com 2019 - 2024. All rights reserved.