gpt4 book ai didi

python - psycopg2 在我造成问题的字符串周围添加引号

转载 作者:行者123 更新时间:2023-11-29 14:29:30 26 4
gpt4 key购买 nike

我有以下脚本:

create_table_WAC = """
create table if not exists %s (
w_geocode text,
C000 text,
CFS04 text,
CFS05 text,
createdate text
)
"""

target_directory = Path(sys.argv[1]).resolve()

for file in target_directory.rglob('*.csv'):

table_name = 'opendata_uscensus_lodes_' + str(file.stem)
print(table_name)

# MAKE SURE THIS IS THE RIGHT TABLE FOR THE FILES
cur.execute(create_table_WAC, (table_name,))

with open(file,'r') as file_in:

# MAKE SURE THIS HAS THE RIGHT TABLE NAME IN THE COPY STATEMENT
cur.copy_expert("copy %s from stdin with csv header delimiter ','", table_name, file_in)

conn.commit()

conn.close()

当我运行它时,它会抛出与 CREATE TABLE 命令相关的错误。我不明白为什么要添加 '',我该如何删除它们?

这里是错误:

psycopg2.ProgrammingError: syntax error at or near "'opendata_uscensus_lodes_ca_wac_SA02_JT03_2003'"
LINE 2: create table if not exists 'opendata_uscensus_lodes_ca_wac_S...

最佳答案

使用 SQL 字符串组合:

from psycopg2 import sql

create_table_WAC = """
create table if not exists {} ( -- note changed placeholder
w_geocode text,
C000 text,
CFS04 text,
CFS05 text,
createdate text
)
"""

# ...

cur.execute(sql.SQL(create_table_WAC).format(sql.Identifier(table_name)))

阅读综合说明in the documentation.

关于python - psycopg2 在我造成问题的字符串周围添加引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53787034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com