def create_table(self, name: str, coulmn: str):
"""This method creates a table in the session.
Args:
name : Name of the table to be created.
coulmn : Column in the table to be created.
Format is "(name data_type condition, name2 data_type2 condition2...)".
"""
self.cur.execute(
query=SQL("CREATE TABLE {name} %s;").format(name=Identifier(name)),
vars=[coulmn]
)
這是方法源代碼。
self.postgres.create_table(name="test", coulmn="(id serial PRIMARY KEY, name text)")
這是測驗代碼。
psycopg2.errors.SyntaxError: ??(error): ?? ??(SyntaxError), "'(id serial PRIMARY KEY, name text)'" ??(near)
LINE 1: CREATE TABLE "test" '(id serial PRIMARY KEY, name文本)';
為什么我會收到語法錯誤?
uj5u.com熱心網友回復:
第一次運行:
import psycopg2
from psycopg2 import sql
name = 'test'
columns = [('id', ' serial PRIMARY KEY,'), ('name', ' text')]
composed_cols = []
for col in columns:
composed_cols.append(sql.Composed([sql.Identifier(col[0]), sql.SQL(col[1])]))
[Composed([Identifier('id'), SQL(' serial PRIMARY KEY,')]),
Composed([Identifier('name'), SQL(' text')])]
qry = sql.SQL("CREATE TABLE {name} ({} {})").format(sql.SQL('').join(composed_cols[0]), sql.SQL('').join(composed_cols[1]), name=sql.Identifier(name))
print(qry.as_string(con))
CREATE TABLE "test" ("id" serial PRIMARY KEY, "name" text)
cur.execute(qry)
con.commit()
\d test
Table "public.test"
Column | Type | Collation | Nullable | Default
-------- --------- ----------- ---------- ----------------------------------
id | integer | | not null | nextval('test_id_seq'::regclass)
name | text | | |
Indexes:
"test_pkey" PRIMARY KEY, btree (id)
基本上將列定義分為兩個部分,名稱/識別符號和型別/約束部分。然后創建一個串列,將這些元素組合成正確的sql物件。通過將串列的元素分別連接到{}列名和型別/約束部分的占位符中來構建查詢字串。使用命名占位符{name}作為表名。需要注意的部分sql.SQL是文字字串,如果它來自外部來源,則需要對其進行驗證。
更新
意識到這可以簡化為:
col_str = '(id serial PRIMARY KEY, name text)'
qry = sql.SQL("CREATE TABLE {name} {cols} ").format(cols=sql.SQL(col_str), name=sql.Identifier(name))
print(qry.as_string(con))
CREATE TABLE "test" (id serial PRIMARY KEY, name text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408059.html
標籤:
