將 Python 資料框架插入至 SQL 資料表

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體

本文描述如何使用 Python 中的 pyodbc 套件,將 pandas 資料框架插入至 SQL 資料庫。

必要條件

  • 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. 選取 [管理套件]。

    Manage packages

  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 Server 中的步驟,以連線到 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

後續步驟