-
I'm trying to convert older code that directly ran I was able to modify most statements I had but had trouble with this: Old Python code: schema="public"
table_name="test"
col_types = [
("a", "integer"),
("b", "text"),
]
...
with conn.cursor() as cur:
sql = f"CREATE TABLE IF NOT EXISTS {schema}.{table_name}"
columns = ", ".join([f'"{name}" {type}' for name, type in col_types])
sql += f" ({columns})"
try:
cur.execute(sql)
conn.commit()
logging.info(f"create table: {sql=}")
except (Exception, psycopg2.DatabaseError) as error:
logging.error(error)
conn.rollback() Logged output:
Attempted new code: from psycopg2.sql import SQL, Identifier, Placeholder
schema="public"
table_name="test"
col_types = [
("a", "integer"),
("b", "text"),
]
...
with conn.cursor() as cur:
sql = SQL("CREATE TABLE IF NOT EXISTS {name} ({cols})").format(
name=Identifier(schema, table_name),
cols=SQL(", ").join(
SQL(" ").join([Identifier(name), SQL(type)])for name, type in self.col_types
),
)
try:
cur.execute(sql)
conn.commit()
logging.info("create table: %s", sql)
except (Exception, psycopg2.DatabaseError) as error:
logging.exception(error) Logged output:
Does anyone know what the correct syntax is for creating a table with |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The error message is not consistent with your code: you have brackets in you code You can use |
Beta Was this translation helpful? Give feedback.
The error message is not consistent with your code: you have brackets in you code
({cols})
that don't appear in the message.You can use
print(sql.as_string(conn))
to figure out what you are doing wrong.