postgresql 使用标识符列表格式化CREATE TABLE查询

hs1ihplo  于 2023-01-08  发布在  PostgreSQL
关注(0)|答案(1)|浏览(129)

我想用Python写一个脚本,从CSV创建一个PostgreSQL表。而不是使用psycopg2.copy_from,我想要一些更个性化和更灵活的东西。
显然,我将读取CSV文件的第一行,并从中获得一个列名称列表,然后我想将此列表转换为在PostgreSQL中创建表时要写入的列列表:

"column_name_1" text,
"column_name_2" text,
"column_name_3" text,
...
"column_name_N" text

(by默认情况下,我希望所有的列都有文本类型;我可能会在以后更改这些类型)。注意我希望列名两边的双引号显示为,因为这些列名可能包含空格或重音字符。
我尝试使用psycopg2.sql.Identifier将列名用双引号括起来,但是失败了,因为我想将这些标识符与“text”连接起来...
以下是我目前尝试的方法:

import psycopg2
import csv 

conn = psycopg2.connect(
                            dbname = "spatialDB",host="localhost",
                            port = 5432, user = "postgres",
                            password="postgres"
                            )

cur = conn.cursor()

FileName = "csv_to_import.csv"
file = open(FileName,'r',encoding='utf-8')
reader = csv.reader(file,delimiter=";")

columns = next(reader)

# The line below is what I wanted to do, but you cannot concatenate 
# an SQL identifier with a string 

#column_types = [psycopg2.sql.Identifier(c) + " text" for c in colums]

# This is what I did instead but it's ugly
column_types = ["\"" + c + "\"  text" for c in columns]

schema = "myschema"
table_name = "import_csv_python"

model_query = "CREATE TABLE {0}.{1}({2});" 
column_list = ",".join(column_types)

query = model_query.format(schema,table_name,column_list)

cur.execute(query)
file.close()
cur.close()
conn.commit()

如何更正此代码以使其使用psycopg2.sql.Identifier函数,从而正确引用列名?(同样的问题适用于参数{0}和{1},它们分别是模式和表名)

kqlmhetl

kqlmhetl1#

使用方法as_string(context)构建列列表并将所有字符串参数转换为Composable:

import psycopg2.sql as sql

column_types = [sql.Identifier(c).as_string(cur) + " text" for c in columns]

schema = sql.Identifier("myschema")
table_name = sql.Identifier("import_csv_python")

model_query = sql.SQL("CREATE TABLE {0}.{1}({2});") 
column_list = sql.SQL(",".join(column_types))

query = model_query.format(schema,table_name,column_list)

相关问题