使用Panadas 2.2.3、sqlite3.version 2.6.0和python 3.12.5, 当使用 to_sql 和 if_exists='append' 时,出现错误“表...已经退出”。我只是尝试将 Pandas df 中的一些数据附加到 SQLite DB 表中。使用 if_exists='replace' 会产生相同的结果。
为了确保数据库连接处于活动状态并且列匹配,我在第一个 try 块中使用了一些简单的打印语句,并在第二个 try 块中使用了失败的 to.sql。第一个块中还使用了同一个表中的“select 语句”。第一个块执行时没有异常,第二个块抛出消息“表“groupedData”已存在”:(请参阅 print('ERROR Try 2'))
源代码:
try:
print(db_conn)
print(table_grouped)
data = [x.keys() for x in db_conn.cursor().execute(f'select * from {table_grouped};').fetchall()]
print(data)
except Error as e:
print('ERROR Try 1')
print(e)
try:
print(df_grouped.head(5))
df_grouped.to_sql(table_grouped, db_conn, if_exists='append', index=False)
#if_exists : {‘fail’, ‘replace’, ‘append’}
db_conn.commit()
except Error as e:
print('ERROR Try 2')
print(e)
输出:
<sqlite3.Connection object at 0x000001C0E7C0EB60>
groupedData
[['CustomerID', 'TotalSalesValue', 'SalesDate']]
CustomerID TotalSalesValue SalesDate
0 12345 400.0 2020-02-01
1 12345 1050.0 2020-02-04
2 12345 10.0 2020-02-10
3 12345 200.0 2021-02-01
4 12345 50.0 2021-02-04
ERROR Try 2
table "groupedData" already exists
事实证明(感谢一位还没有 stackoverflow 帐户的朋友)问题是区分大小写。我将 SQLite 数据库表命名为“GroupedData”,并在 Python 中将“groupedData”与 Pandas 一起使用。
虽然 SQL 表名通常不区分大小写,而且 sqlite3 对表名也不区分大小写...
db_conn = sqlite3.connect(db_file_path)
db_conn.cursor().execute(f'select * from {table_grouped};').fetchall()
... Pandas 的 to_sql() 显示区分大小写的行为,并显示错误消息,未正确指示问题。使用 table_grouped='GroupedData',第二个 try 块适用于“追加”和“替换”。
我将使用(https://github.com/pandas-dev/pandas/issues/new?)向 Pandas 报告该主题并链接 stackoverflow 问题。我的建议是提供更具体的错误消息或将 to_sql() 的行为更改为不区分大小写。