每当我想将 pandas 数据框中的数据插入到 postgresql 数据库中时,我都会收到此错误 error: extra data after last expected column CONTEXT: COPY recommendations, line 1: "0,4070,"[5963, 8257, 9974, 7546, 11251, 5203, 102888, 8098, 101198, 10950]""数据帧由三列组成,第一列和第二列是整数类型,第三列是整数列表。我使用下面的函数在 PostgreSQL 中创建了一个表def create_table(query: str) -> None:""":param query: A string of the query to create table in the database:return: None"""try: logger.info("Creating the table in the database") conn = psycopg2.connect(host=HOST, dbname=DATABASE_NAME, user=USER, password=PASSWORD, port=PORT) cur = conn.cursor() cur.execute(query) conn.commit() logger.info("Successfully created a table in the database using this query {}".format(query)) returnexcept (Exception, psycopg2.Error) as e: logger.error("An error occurred while creating a table using the query {} with exception {}".format(query, e))finally: if conn is not None: conn.close() logger.info("Connection closed!")传递到该函数的查询是这样的:create_table_query = '''CREATE TABLE Recommendations(id INT NOT NULL,applicantId INT NOT NULL,recommendation INTEGER[], PRIMARY KEY(id), CONSTRAINT applicantIdFOREIGN KEY(applicantId)REFERENCES public."Applicant"(id)ON DELETE CASCADEON UPDATE CASCADE ); '''然后,我使用下面的函数将数据框复制到 postgres 中创建的表中。def copy_from_file(df: pd.DataFrame, table: str = "recommendations") -> None: """ Here we are going save the dataframe on disk as a csv file, load the csv file and use copy_from() to copy it to the table """然后我仍然得到这个问题,error: extra data after last expected column CONTEXT: COPY recommendations, line 1: "0,4070,"[5963, 8257, 9974, 7546, 11251, 5203, 102888, 8098, 101198, 10950]""请问您对如何解决这个问题有什么建议吗?谢谢
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
copy_from
使用文本格式,而不是 csv 格式。您告诉它用作,
分隔符,但这不会改变它尝试使用的保护方法。因此,引号内的逗号不被视为受保护,它们被视为字段分隔符,所以当然它们太多了。
我认为你需要使用copy_expert
并告诉它使用该csv
格式。
添加回答
举报
0/150
提交
取消