I'm facing some troubles when trying to execute a PostgreSQL CREATE TABLE
query with a dictionary of parameters using psycopg:
#!/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
The curs.execute()
calls either raise:
SyntaxError: syntax error at or near "%"
with the two firsts queries or:SyntaxError: type modifiers must be simple constants or identifiers
with the last onehttps://www.psycopg.org/psycopg3/docs/basic/params.html
Python: 3.10
psycopg: 3.2.3
PostgreSQL: 16
As the documentation for SQL.format
states, SQL.format
uses the same placeholder syntax as str.format
, i.e. {CRS}
and not %(CRS)s
.
d = {"CRS": 4326}
raw = "CREATE TABLE foo (id INT, geom geometry('Point',{CRS}));"
query0 = psycopg.sql.SQL(raw).format(**d)