如何在python中将另一个Excel数据附加到sqlite3数据库中?

时间:2019-07-18 11:18:53

标签: python-3.x

我需要将多个Excel文件数据导入一个SQLite数据库,这些每周生成的Excel文件具有相同的命名约定和数据结构。

在我的代码中,第一个文件数据成功导入,当我尝试导入第二个文件时,这给了我一个错误。

enter image description here

import sqlite3
import pandas as pd
filename="cps"
con=sqlite3.connect(filename+".db")
wb = pd.read_excel('CPS\cps29.xlsx',sheet_name = None)
for sheet in wb:

    wb[sheet].to_sql(sheet,con,index=False)
    con.commit()
    con.close()

我需要将数据追加到数据库中。

1 个答案:

答案 0 :(得分:1)

如果表已经存在,请使用if_exists='append'插入新行(如果表不存在,则会创建新行):

for sheet in wb:
    wb[sheet].to_sql(sheet, con, index=False, if_exists='append')
    con.commit()
con.close()

还要注意,con.close()内不应调用for-loop。提交完所有数据后,在for循环之后调用一次。