Hướng dẫn insert dataframe to sql server - python - chèn khung dữ liệu vào máy chủ sql - python

Bỏ qua nội dung chính

Trình duyệt này không còn được hỗ trợ.

Nâng cấp lên Microsoft Edge để tận dụng các tính năng mới nhất, cập nhật bảo mật và hỗ trợ kỹ thuật.

Chèn Python DataFrame vào bảng SQL

  • Bài báo
  • 18/11/2022
  • 2 phút để đọc

Trong bài viết này

Áp dụng cho: SQL Server (tất cả các phiên bản được hỗ trợ) Cơ sở dữ liệu Azure SQL Azure SQL được quản lý

Hướng dẫn insert dataframe to sql server - python - chèn khung dữ liệu vào máy chủ sql - python
SQL Server (all supported versions) Azure SQL Database Azure SQL Managed Instance

Bài viết này mô tả cách chèn khung dữ liệu gấu trúc vào cơ sở dữ liệu SQL bằng cách sử dụng gói PYODBC trong Python.

Điều kiện tiên quyết

  • SQL Server cho Windows hoặc cho Linux

  • Cơ sở dữ liệu Azure SQL

  • Azure SQL được quản lý

  • SQL Server Management Studio để khôi phục cơ sở dữ liệu mẫu cho phiên bản được quản lý của Azure SQL.

  • Azure Data Studio. Để cài đặt, xem Tải xuống và cài đặt Azure Data Studio.

  • Thực hiện theo các bước trong cơ sở dữ liệu mẫu AdventureWorks để khôi phục phiên bản OLTP của cơ sở dữ liệu mẫu AdventureWorks cho phiên bản SQL Server của bạn.

    Bạn có thể xác minh rằng cơ sở dữ liệu đã được khôi phục chính xác bằng cách truy vấn bảng HumanResource.Depment:HumanResources.Department table:

    USE AdventureWorks;
    SELECT * FROM HumanResources.Department;
    

Cài đặt các gói Python

  1. Trong Azure Data Studio, hãy mở một cuốn sổ mới và kết nối với hạt nhân Python 3.

  2. Chọn Quản lý gói.Manage Packages.

    Hướng dẫn insert dataframe to sql server - python - chèn khung dữ liệu vào máy chủ sql - python

  3. Trong ngăn Quản lý gói, chọn Tab Thêm mới.Manage Packages pane, select the Add new tab.

  4. Đối với mỗi gói sau, nhập tên gói, nhấp vào Tìm kiếm, sau đó nhấp vào Cài đặt.Search, then click Install.

    • Pyodbc
    • gấu trúc

Tạo tệp CSV mẫu

Sao chép văn bản sau và lưu nó vào một tệp có tên 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

Tạo bảng cơ sở dữ liệu mới

  1. Thực hiện theo các bước trong Kết nối với SQL Server để kết nối với cơ sở dữ liệu AdventureWorks.

  2. Tạo một bảng có tên HumanResource.DepmentTest. Bảng SQL sẽ được sử dụng để chèn dữ liệu.HumanResources.DepartmentTest. The SQL table will be used for the dataframe insertion.

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

Tải DataFrame từ tệp CSV

Sử dụng gói Python pandas để tạo DataFrame, tải tệp CSV và sau đó tải DataFrame vào bảng SQL mới, HumanResource.DepartmentTest.HumanResources.DepartmentTest.

  1. Kết nối với hạt nhân Python 3.Python 3 kernel.

  2. Dán mã sau vào ô mã, cập nhật mã với các giá trị chính xác cho server, database,

    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
    
    0,
    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 và vị trí của tệp 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. Chạy ô.

Xác nhận dữ liệu trong cơ sở dữ liệu

Kết nối với cơ sở dữ liệu SQL Kernel và AdventureWorks và chạy câu lệnh SQL sau để xác nhận bảng được tải thành công dữ liệu từ DataFrame.

SELECT count(*) from HumanResources.DepartmentTest;

Kết quả

(No column name)
16

Bước tiếp theo

  • Vẽ biểu đồ để khám phá dữ liệu với Python

Nhận xét

Gửi và xem phản hồi cho