Hướng dẫn python insert into sql server - python chèn vào máy chủ sql

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
  • 01/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 python insert into sql server - python chèn vào máy chủ sql
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 python insert into sql server - python chèn vào máy chủ sql

  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

Làm cách nào để chuyển dữ liệu từ Python sang SQL?

Các bước để nhập tệp CSV vào SQL Server bằng Python..
Bước 1: Chuẩn bị tệp CSV. ....
Bước 2: Nhập tệp CSV vào DataFrame. ....
Bước 3: Kết nối Python với SQL Server. ....
Bước 4: Tạo bảng trong SQL Server bằng Python. ....
Bước 5: Chèn dữ liệu DataFrame vào bảng. ....
Bước 6: Thực hiện kiểm tra ..

Python có thể tương tác với SQL Server không?

Bạn có thể kết nối với cơ sở dữ liệu SQL bằng Python trên Windows, Linux hoặc MacOS..

Làm thế nào để bạn chèn nhiều hàng trong SQL bằng Python?

Điều gì sẽ xảy ra nếu bạn muốn chèn nhiều hàng vào bảng trong một truy vấn chèn từ ứng dụng Python.Sử dụng hàm EXECUTEMANY () của con trỏ để chèn nhiều bản ghi vào bảng.Cú pháp của phương thức EXECUTEMANY ().

Bạn có thể chèn vào SQL không?

Nếu bạn muốn thêm dữ liệu vào bảng SQL của mình, thì bạn có thể sử dụng câu lệnh INSERT.Dưới đây là cú pháp cơ bản để thêm các hàng vào bảng SQL của bạn: chèn vào các giá trị Table_Name (cột1, cột2, cột3, v.v.) (value1, value2, value3, v.v.);Dòng mã thứ hai là nơi bạn sẽ thêm các giá trị cho các hàng.you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.