【发布时间】:2021-07-17 09:17:13
【问题描述】:
我正在尝试使用 CSV 文件在 DB 中插入数据。
import psycopg2 #import the postgres library
#connect to the database
conn = psycopg2.connect(host='1.11.11.111',
dbname='postgres',
user='postgres',
password='myPassword',
port='1234')
#create a cursor object
#cursor object is used to interact with the database
cur = conn.cursor()
#open the csv file using python standard file I/O
#copy file into the table just created
with open("C:/Users/Harshal/Desktop/tar.csv", 'r') as f:
next(f)
cur.copy_from(f, 'geotargets_india',sep=',')
conn.commit()
conn.close()
f.close()
我的表如下:
create table public.geotargets_india(
Criteria_ID integer not null,
Name character varying(50) COLLATE pg_catalog."default" NOT NULL,
Canonical_Name character varying(100) COLLATE pg_catalog."default" NOT NULL,
Parent_ID NUMERIC(10,2),
Country_Code character varying(10) COLLATE pg_catalog."default" NOT NULL,
Target_Type character varying(50) COLLATE pg_catalog."default" NOT NULL,
Status character varying(50) COLLATE pg_catalog."default" NOT NULL
)
我的 CSV 看起来像:
我得到的错误是:
例如,如果仔细查看我的 csv 行:1007740,Hyderabad,"Hyderabad,Telangana,India",9061642.0,IN,City,Active 。在这里,Canonical_Name 有“,”分隔的字符串,这会导致错误,并假设 CSV 中的列比表中的多。如何解决这个问题?
注意:我假设错误只是由于这个原因。
CSV Link
【问题讨论】:
标签: python postgresql csv psycopg2