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

标签 python postgresql csv psycopg2

我正在尝试使用 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/

相关文章:

postgresql - 在 PostgreSQL 中使用 htmlentities 存储的字段,如何搜索(sql select)特殊字符,例如 < 而不进行 < 搜索?

php - 可以在 FreeBSD 10.3 中安装没有依赖项的 pkg 吗?

python - 使用字符串日期对 pandas csv 列表进行排序

以 Python 方式将 header 添加到 csv 文件

csv - 将 csv 文件添加到 HTTP POST

python - 斐波那契在 Python 中很奇怪

python - Kivy 未检测到目录中的文件

sql - postgres 中的子查询或连接联合?

python - 取一个张量的一个元素,该元素也在另一个张量中

python - Django 模型表单集和命名 url