【问题标题】:Why is Psycopg2 having a hard time parsing my commas in a CSV为什么 Psycopg2 很难在 CSV 中解析我的逗号
【发布时间】:2019-01-03 09:16:45
【问题描述】:

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

此数据将用于 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(?,?,?,?,?,?...

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

【问题讨论】:

  • Psycopg 使用 %s 作为占位符,而不是 ?

标签: python postgresql csv psycopg2


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多