將 SQL 資料表的資料插入 Python pandas 資料框架

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

本文描述如何使用 Python 中的 pyodbc 套件,將 SQL 資料插入 pandas 資料框架。 資料框架內所含資料列和資料行可用於進一步的資料探索。

必要條件

驗證還原的資料庫

您可透過查詢 Person.CountryRegion 資料表驗證還原的資料庫是否存在:

USE AdventureWorks;
SELECT * FROM Person.CountryRegion;

安裝 Python 套件

下載及安裝 Azure Data Studio

安裝下列 Python 套件:

  • pyodbc
  • pandas

若要安裝這些套件:

  1. 在 Azure Data Studio 筆記本中,選取 [管理套件]。
  2. 在 [管理套件] 窗格中,選取 [新增] 索引標籤。
  3. 針對每個下列套件,輸入套件名稱,按一下 [搜尋],然後按一下 [安裝]。

插入資料

使用下列指令碼來從 Person.CountryRegion 資料表選取資料,並插入資料框架。 編輯連接字串變數 'server'、'database'、'username' 和 'password' 以連線到 SQL。

建立新的筆記本:

  1. 在 Azure Data Studio 中,選取 [檔案],然後選取 [新增筆記本]。
  2. 在筆記本中,選取核心 [Python3],然後選取 [+程式碼]。
  3. 將程式碼貼到筆記本中,選取 [全部執行]。
import pyodbc
import pandas as pd
# Some other example server values are
# server = 'localhost\sqlexpress' # for a named instance
# server = 'myserver,port' # to specify an alternate port
server = 'servername' 
database = 'AdventureWorks' 
username = 'yourusername' 
password = 'databasename'  
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# select 26 rows from SQL table to insert in dataframe.
query = "SELECT [CountryRegionCode], [Name] FROM Person.CountryRegion;"
df = pd.read_sql(query, cnxn)
print(df.head(26))

輸出

以上指令碼中 print 命令會顯示 pandas 資料框架 df 的資料列。

CountryRegionCode                 Name
0                 AF          Afghanistan
1                 AL              Albania
2                 DZ              Algeria
3                 AS       American Samoa
4                 AD              Andorra
5                 AO               Angola
6                 AI             Anguilla
7                 AQ           Antarctica
8                 AG  Antigua and Barbuda
9                 AR            Argentina
10                AM              Armenia
11                AW                Aruba
12                AU            Australia
13                AT              Austria
14                AZ           Azerbaijan
15                BS         Bahamas, The
16                BH              Bahrain
17                BD           Bangladesh
18                BB             Barbados
19                BY              Belarus
20                BE              Belgium
21                BZ               Belize
22                BJ                Benin
23                BM              Bermuda
24                BT               Bhutan
25                BO              Bolivia

後續步驟