【问题标题】:how to create table into SQLite3 from importing excel data in python?如何通过在 python 中导入 excel 数据在 SQLite3 中创建表?
【发布时间】:2019-11-29 02:24:18
【问题描述】:

在我的代码中,我使用 python 将数据从 excel 文件导入 SQLite 数据库。

它不会给出任何错误,但它会将每个 excel 列名转换为一个表格。

我有多个数据结构相同的 excel 文件,每个文件包含 40K 行和 52 列。

当我使用 python 代码将这些文件数据导入 SQLite 数据库时,它会将每个列标题名称转换为一个表。

import sqlite3
import pandas as pd

filename= gui_fname()
con=sqlite3.connect("cps.db")
wb = pd.read_excel(filename,sheet_name ='Sheet2')
for sheet in wb: 
    wb[sheet].to_sql(sheet,con,index=False,if_exists = 'append')
con.commit()
con.close()

它应该创建一个名称为我正在导入的工作表的表格。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    我做了一些尝试并找到了解决方案: 我只是将 con.commit() 放在 for 循环中,它按要求工作,但我没有得到逻辑。

    如果有人能向我解释这一点,我将不胜感激。

    import sqlite3
    import pandas as pd
    
    filename= gui_fname()
    con=sqlite3.connect("cps.db")
    wb = pd.read_excel(filename,sheet_name = 'Sheet2')
    for sheet in wb:
    
        wb[sheet].to_sql(sheet,con,index=False,if_exists = 'append')
        con.commit()
    con.close()
    

    【讨论】:

      【解决方案2】:
      import pandas as pd
      def import_excel_to_sqlite_db(excelFile):
          df = pd.read_excel(excelFile)
          con = sqlite3.connect("SQLite.db")
          cur = con.cursor()
          results = cur.execute("Select * from TableName")
          final = df.to_sql("TableName", con, if_exists="append", index=False)
          pd.DataFrame(results, columns=final)
          con.commit()
          cur.close()
      

      【讨论】:

        猜你喜欢
        • 2015-01-16
        • 2019-07-19
        • 1970-01-01
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        • 1970-01-01
        相关资源
        最近更新 更多