Python データフレームを SQL テーブルに挿入する

適用対象:SQL ServerAzure SQL DatabaseAzure SQL Managed Instance

この記事では、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 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

次のステップ