【问题标题】:trying to import csv file into postgresql database through python3试图通过python3将csv文件导入postgresql数据库
【发布时间】:2019-10-27 08:06:40
【问题描述】:

这是我的 cs50w 项目,我正在尝试将 books.csv 文件导入 postgresql 数据库,但我遇到了一些错误,我认为我的脚本有问题,有人可以纠正它...

import psycopg2
import csv

#For connecting to the database
conn = psycopg2.connect("host=hostname_here port=5432 dbname=dbname_here user=username_here password=pass_here")
cur = conn.cursor()

#importing csv file
with open('books.csv', 'r') as f:
    reader = csv.reader(f)
next(reader)

for row in reader:
    cur.execute("INSERT INTO book VALUES (%s, %s, %s, %s)",
                row
                )
    conn.commit()


Traceback (most recent call last):
  File "import.py", line 15, in <module>
  row
psycopg2.errors.SyntaxError: INSERT has more expressions than target      columns
LINE 1: INSERT INTO book VALUES ('0380795272', 'Krondor: The Betraya...

csv 文件样本: sample of csv file :

【问题讨论】:

  • 请显示您的 CSV 文件中的几行。
  • 我添加了我的 csv 文件的样本

标签: python python-3.x postgresql flask psycopg2


【解决方案1】:

INSERT 的表达式比目标列多。

您正试图在少于 4 列的表中插入包含 4 个值的行。

但是,如果表格确实有 4 列,则需要查看数据源(books.cvs)。源数据可能包含一些单引号或逗号。从文件中删除有问题的数据或修改您的程序以正确处理数据。

【讨论】:

    【解决方案2】:

    在我的 postgres 表中解决了问题,我将 isbn 设置为整数,但我没有看到带有它的字母现在我将 isbn 列更改为 varchar,问题就解决了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-20
      • 2014-08-18
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多