从CSV文件插入到具有整数值类型的PostgreSQL表

时间:2017-08-10 08:18:46

标签: python postgresql csv integer psycopg2

  I want to insert data from a CSV file into a PostgreSQL table. The table 

结构如下。但我无法输入INTEGER类型值。 它显示的错误如下 -         DataError:整数的输入语法无效:" vendor_phone"         第1行:... vendor_phone,vendor_address)VALUES(' vendor_name',' vendor_ph ...

如果我使用VARCHAR类型,它工作正常。但我需要使用整数值。

   CREATE TABLE vendors (
        vendor_id SERIAL PRIMARY KEY,
        vendor_name VARCHAR(100) NOT NULL,
        vendor_phone INTEGER,
        vendor_address VARCHAR(255) NOT NULL 
    )
    import psycopg2
    import csv

    database = psycopg2.connect (database = "supplier", user="postgres", password="1234", host="localhost", port="5432")

cursor = database.cursor()

    vendor_data = csv.reader(open('vendors.csv'),delimiter=',')

    for row in vendor_data:

        cursor.execute("INSERT INTO vendors (vendor_name,vendor_phone,vendor_address)"\
            "VALUES (%s,%s,%s)",
           row)

    print("CSV data imported")

    cursor.close()
    database.commit()
    database.close()

1 个答案:

答案 0 :(得分:0)

而不是光标,您可以使用以下语句将数据直接从CSV加载到表格,该表格会跳过CSV文件的标题

COPY vendors (vendor_name,vendor_phone,vendor_address) FROM 'vendors.csv' CSV HEADER;