在尝试使用 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
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)