gpt4 book ai didi

python - 为什么 Psycopg2 很难在 CSV 中解析我的逗号

转载 作者:行者123 更新时间:2023-11-29 12:16:00 25 4
gpt4 key购买 nike

我正在尝试使用 Psycopg2 将 CSV 文件中的数据动态导入到 PostGreSQL 数据库中。我的 CSV 文件 header 解析正确,但数据被逗号挂起并引发错误。

此数据将用于 Azure 数据库实例。我试过从 .join 语句中删除逗号,但这搞砸了格式并仍然抛出类似的错误。我还填写了缺失的数据,因为我认为情况也可能如此。

这是我使用的数据示例:

 first_name,Last_name,mothers_maiden_name,date_of_birth,participant_age,gender,homeless,runaway,training_program,Created
Tiffany,Wilson,N/A,02-05-1994,24,Female,N/A,N/A,Employment Training Assistance ,12-14-2018 12:44:06

代码片段:

with open('Assistance Request Form-participant-Info.csv', 'r') as f:
reader = csv.reader(f)
columns = next(reader)
query = 'insert into participant({0}) values({1})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))
print(query)
cursor = connection.cursor()
for data in reader:
cursor.execute(query,data)
cursor.commit()

和错误消息/StackTrace:

psycopg2.ProgrammingError: syntax error at or near ","
LINE 1: ...omeless,runaway,training_program,Created) values(?,?,?,?,?,?...

预期的输出应该是插入语句将每个数据点动态加载到表的正确位置。

最佳答案

使用 '%s' 作为 cursor.execute() 中的占位符。

query = query.format(','.join(columns), ','.join(['%s'] * len(columns)))
cursor = connection.cursor()
for data in reader:
cursor.execute(query,data)
connection.commit() # not cursor.commit()

关于python - 为什么 Psycopg2 很难在 CSV 中解析我的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54019299/

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