【问题标题】:Import .csv file to PostgreSQL and add an autoincrementing ID in the first column将 .csv 文件导入 PostgreSQL 并在第一列添加自动递增 ID
【发布时间】:2019-10-17 13:20:59
【问题描述】:

我已经下载了一个用于测试目的的 csv 文件,并希望将所有数据上传到 postgresql 数据库。但是,我需要有一个自动递增的 ID 作为数据库的第一列。最初,我使用 SQL Query 创建了数据库:

CREATE TABLE pps3
(  id integer NOT NULL DEFAULT 
   nextval('products_product_id_seq'::regclass),
  "brandname" character varying(25),
  "type1" integer,
  "type2" integer,
  "type3" integer,
  "Total" integer ) 

CSV 数据:

"brandname","type1","type2","type3","Total"
"brand1","0","0","32","32"
"brand1","0","12","0","12"

我尝试使用以下代码从 CSV 中移动数据:


import csv
import psycopg2

conn = psycopg2.connect("host=localhost dbname=my_django_db user=postgres")
cur = conn.cursor()
with open('PPS-Sep.csv', 'r') as f:
    reader = csv.reader(f)
    next(reader) # Skip the header row.
    for row in reader:
        cur.execute(
        "INSERT INTO pps3 VALUES (%s, %s, %s, %s,%s)",row)

conn.commit()

如果我不创建初始 ID 列,这可以正常工作。

但是,如果我这样运行它,我会收到一条错误消息,提示我正在尝试将品牌名称插入 ID。

关于如何解决这个问题的任何想法?

【问题讨论】:

  • 您可以引用要插入的列,例如:cur.execute( "INSERT INTO pps3 (brandname, type1, type2, type3, total) VALUES (%s, %s, %s, %s,%s)",row)
  • 我希望有一个更懒惰的解决方案,因为列数超过 50.. 但我也会尝试 :))
  • 那是 SQL。它希望您尽可能明确,而快捷方式通常会导致大量胃灼热。
  • 感谢 JNevill !我现在将对其进行测试。我认为它应该工作。你认为我应该把列名放在这样的括号中:“brandname”...等还是直接说明
  • 这取决于你。如果您的列名可能是保留关键字,并且您正在自动编写此代码,则将它们放在双引号中,否则您可以毫不费力地将它们去掉。

标签: django python-3.x postgresql


【解决方案1】:

尝试改变:

INSERT INTO pps3 VALUES (%s, %s, %s, %s)

INSERT INTO pps3(type1, type2, type3, Total) VALUES (%s, %s, %s, %s)

在不提供列的情况下使用 INSERT INTO 时,postgres 按原始顺序使用表中的所有列。

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2020-09-05
    • 2017-04-13
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2014-10-02
    • 2014-07-29
    相关资源
    最近更新 更多