每当我想将 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))
return
except (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 applicantId
FOREIGN KEY(applicantId)
REFERENCES public."Applicant"(id)
ON DELETE CASCADE
ON 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]""请问您对如何解决这个问题有什么建议吗?谢谢
四季花海
相关分类