使用Python将Excel表导入SQL数据库

发布于 2025-01-10 19:45:24 字数 1478 浏览 0 评论 0原文

我有由第 3 方程序创建的 SQL 数据库,我正在使用 python 将一些数据从 Excel 表导入到 SQL 数据库。这里是数据库和excel表格的预览;

sql 和 excel 列的名称完全匹配。这是我用来导入的代码;

import pandas as pd
import sqlite3

#Paths
excel_path="C:/users/user/desktop/ACC_Import.xlsx"
sql_db_path="c:/users/P6_BD_DataBase_001"

#Defs
df=pd.read_excel(excel_path, dtype={"ACCT_SHORT_NAME":object}) #this dtype important, pandas turns to int which we don't want to ...
conn=sqlite3.connect(sql_db_path)
cur=conn.cursor()

def insert_excel_to_sql(df):
    for row in df.itertuples():
        data_tuple=(row.ACCT_ID,
        row.PARENT_ACCT_ID,
        row.ACCT_SEQ_NUM,
        row.ACCT_NAME,
        row.ACCT_SHORT_NAME,
        row.ACCT_DESCR,
        row.CREATE_DATE,
        row.CREATE_USER,
        row.UPDATE_DATE,
        row.UPDATE_USER,
        row.DELETE_SESSION_ID,
        row.DELETE_DATE)
        sqlite_insert_with_param='''
                    INSERT INTO ACCOUNT (ACCT_ID,PARENT_ACCT_ID,ACCT_SEQ_NUM,ACCT_NAME,
                    ACCT_SHORT_NAME,ACCT_DESCR,CREATE_DATE,CREATE_USER,
                    UPDATE_DATE,UPDATE_USER,DELETE_SESSION_ID,DELETE_DATE)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?);
                    '''
        cur.execute(sqlite_insert_with_param,data_tuple)
    conn.commit()

仍然一一输入所有列的名称,我确信它们是完全相同的。

有没有其他方法可以通过不一一输入所有列名来将 excel 表(sql 和 excel 列名完全相同)导入到 sql 中?

I have SQL database created by 3rd party program and I am importing some datas from excel table to sql db with python. Here is the previews of database and excel table;

enter image description here

As you see sql and excel columns' name are matched exactly. and here is code I use to import;

import pandas as pd
import sqlite3

#Paths
excel_path="C:/users/user/desktop/ACC_Import.xlsx"
sql_db_path="c:/users/P6_BD_DataBase_001"

#Defs
df=pd.read_excel(excel_path, dtype={"ACCT_SHORT_NAME":object}) #this dtype important, pandas turns to int which we don't want to ...
conn=sqlite3.connect(sql_db_path)
cur=conn.cursor()

def insert_excel_to_sql(df):
    for row in df.itertuples():
        data_tuple=(row.ACCT_ID,
        row.PARENT_ACCT_ID,
        row.ACCT_SEQ_NUM,
        row.ACCT_NAME,
        row.ACCT_SHORT_NAME,
        row.ACCT_DESCR,
        row.CREATE_DATE,
        row.CREATE_USER,
        row.UPDATE_DATE,
        row.UPDATE_USER,
        row.DELETE_SESSION_ID,
        row.DELETE_DATE)
        sqlite_insert_with_param='''
                    INSERT INTO ACCOUNT (ACCT_ID,PARENT_ACCT_ID,ACCT_SEQ_NUM,ACCT_NAME,
                    ACCT_SHORT_NAME,ACCT_DESCR,CREATE_DATE,CREATE_USER,
                    UPDATE_DATE,UPDATE_USER,DELETE_SESSION_ID,DELETE_DATE)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?);
                    '''
        cur.execute(sqlite_insert_with_param,data_tuple)
    conn.commit()

I still type all columns' names one by one which I am sure that they are exactly the same.

Is there any other way importing excel table (sql and excel column names are exactly same) to sql by NOT typing all column names one by one ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染火枫林 2025-01-17 19:45:24

来自 sqlite INSERT 文档

INSERT INTO 表 VALUES(...);

第一个表单(带有“VALUES”关键字)在现有表中创建一个或多个新行。如果省略表名后面的列名列表,则插入到每行中的值的数量必须与表中的列数相同。在这种情况下,计算 VALUES 列表中每一项最左侧表达式的结果将插入到每个新行的最左侧列中,对于每个后续表达式依此类推。

因此,不必在 INSERT 语句中键入所有列名。

From the sqlite INSERT doc:

INSERT INTO table VALUES(...);

The first form (with the "VALUES" keyword) creates one or more new rows in an existing table. If the column-name list after table-name is omitted then the number of values inserted into each row must be the same as the number of columns in the table. In this case the result of evaluating the left-most expression from each term of the VALUES list is inserted into the left-most column of each new row, and so forth for each subsequent expression.

Therefore it is not necessary to type all the column names in the INSERT statement.

清君侧 2025-01-17 19:45:24

首先,@DinoCoderSaurus 是正确的,没有必要在 INSERT 语句中键入列名。对于 df 列名称,我使用此路径

df=pd.read_excel("Acc_Import.xlsx",dtype=object)

Reading excel table with dtypes as an object

for index in range(len(df)):
    row_tuple=tuple(df.iloc[index].to_list())
    cur.execute('''INSERT INTO ACCOUNT VALUES (?,?,?,?,?,?,?,?,?,?,?,?);
                    ''',row_tuple)

随着读取“df dtype=object”返回 row_tuple 项目的类型“int,str,float”,因此,我能够将Excel数据导入SQL数据库。图片如下;

输入图片此处描述

如果我不使用 dtype=object 读取 df;

row_tuple=tuple(df.iloc[index].to_list())

row_tuple 项的 dtypes 返回“numpy.int64、numpy.float64”,这会在将 excel 表导入到 sql db 时导致“数据不匹配错误”。图片如下;

输入图片此处描述

First, @DinoCoderSaurus is right, not necessary to type column names in INSERT statement. For df column names, I used this path

df=pd.read_excel("Acc_Import.xlsx",dtype=object)

Reading excel table with dtypes as an object

for index in range(len(df)):
    row_tuple=tuple(df.iloc[index].to_list())
    cur.execute('''INSERT INTO ACCOUNT VALUES (?,?,?,?,?,?,?,?,?,?,?,?);
                    ''',row_tuple)

With reading "df dtype=object" returns row_tuple items' type "int,str,float" so, I was able to import excel datas to SQL database. image as below;

enter image description here

If I don't read df with dtype=object;

row_tuple=tuple(df.iloc[index].to_list())

row_tuple items' dtypes return "numpy.int64, numpy.float64" which causes "data mismatch error" when importing excel table to sql db. Image as below ;

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文