将 Python 数据帧插入 SQL 表

适用于:SQL ServerAzure SQL 数据库Azure SQL 托管实例

本文介绍如何使用 Python 中的 pyodbc 包在 SQL 数据库中插入 pandas 数据帧。

先决条件

  • Azure Data Studio。 要下载,请参阅下载并安装 Azure Data Studio

  • 按照 AdventureWorks 示例数据库中的步骤,为 SQL Server 版本还原 AdventureWorks 示例数据库的 OLTP 版本。

    可以通过查询“HumanResources.Department”表来验证数据库是否已正确还原:

    USE AdventureWorks;
    SELECT * FROM HumanResources.Department;
    

安装 Python 包

  1. 在 Azure Data Studio 中,打开新的笔记本并连接到 Python 3 内核。

  2. 选择“管理包”。

    管理包

  3. 在“管理包”窗格中,选择“添加新包”选项卡。

  4. 对于以下每个包,输入包名称,单击“搜索”,然后单击“安装”。

    • pyodbc
    • pandas

创建示例 CSV 文件

复制以下文本并将其保存到名为“department.csv”的文件。

DepartmentID,Name,GroupName,
1,Engineering,Research and Development,
2,Tool Design,Research and Development,
3,Sales,Sales and Marketing,
4,Marketing,Sales and Marketing,
5,Purchasing,Inventory Management,
6,Research and Development,Research and Development,
7,Production,Manufacturing,
8,Production Control,Manufacturing,
9,Human Resources,Executive General and Administration,
10,Finance,Executive General and Administration,
11,Information Services,Executive General and Administration,
12,Document Control,Quality Assurance,
13,Quality Assurance,Quality Assurance,
14,Facilities and Maintenance,Executive General and Administration,
15,Shipping and Receiving,Inventory Management,
16,Executive,Executive General and Administration

新建数据库表

  1. 按照连接到 SQL 服务器中的步骤,连接到 AdventureWorks 数据库。

  2. 创建名为“HumanResources.DepartmentTest”的表。 SQL 表将用于插入数据帧。

    CREATE TABLE [HumanResources].[DepartmentTest](
    [DepartmentID] [smallint] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [GroupName] [dbo].[Name] NOT NULL
    )
    GO
    

从 CSV 文件加载数据帧

使用 Python pandas 包创建数据帧、加载 CSV 文件,然后将数据帧加载到新的 SQL 表“HumanResources.DepartmentTest”。

  1. 连接到“Python 3”内核。

  2. 将以下代码粘贴到代码单元格中,从而通过 serverdatabaseusernamepassword 的正确值和 CSV 文件的位置更新代码。

    import pyodbc
    import pandas as pd
    # insert data from csv file into dataframe.
    # working directory for csv file: type "pwd" in Azure Data Studio or Linux
    # working directory in Windows c:\users\username
    df = pd.read_csv("c:\\user\\username\department.csv")
    # Some other example server values are
    # server = 'localhost\sqlexpress' # for a named instance
    # server = 'myserver,port' # to specify an alternate port
    server = 'yourservername' 
    database = 'AdventureWorks' 
    username = 'username' 
    password = 'yourpassword' 
    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
    cursor = cnxn.cursor()
    # Insert Dataframe into SQL Server:
    for index, row in df.iterrows():
         cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
    cnxn.commit()
    cursor.close()
    
  3. 运行单元。

确认数据库中的数据

连接到 SQL 内核和 AdventureWorks 数据库,并运行以下 SQL 语句以确认表已成功加载数据帧中的数据。

SELECT count(*) from HumanResources.DepartmentTest;

结果

(No column name)
16

后续步骤