Trong SQL Server Management Studio [SSMS], việc dễ dàng sử dụng thủ tục bên ngoài sp_execute_external_script đã [và vẫn sẽ] được thảo luận nhiều lần. Nhưng lý do cho bài đăng trên blog ngắn này là do việc thay đổi môi trường Python bằng cách sử dụng quản lý gói/mô-đun Conda trong Microsoft SQL Server [Dịch vụ], theo nghĩa đen là không thể. Các tình huống mà bạn muốn xây dựng một tập hợp mô-đun [gói] lớn hơn nhưng không thể tương thích với SQL Server hoặc Conda của mình, thì bạn cần thiết lập một môi trường ảo mới và bắt đầu sử dụng Python từ đó
Giao tiếp với cơ sở dữ liệu để tải dữ liệu vào môi trường python khác nhau không phải là vấn đề. Mô-đun Python Pandas là một cách dễ dàng để lưu trữ tập dữ liệu ở định dạng giống như bảng, được gọi là khung dữ liệu. Pandas là gói python rất mạnh để xử lý cấu trúc dữ liệu và phân tích dữ liệu
Đang tải dữ liệu từ SQL Server sang Python pandas dataframe
Nhiệm vụ cơ bản này là thứ mà mọi nhà phân tích dữ liệu, kỹ sư dữ liệu, nhà thống kê và nhà khoa học dữ liệu sẽ sử dụng trong công việc hàng ngày. Trích xuất dữ liệu từ cơ sở dữ liệu Microsoft SQL Server bằng truy vấn SQL và lưu trữ nó trong các đối tượng pandas [hoặc numpy]
Với đoạn mã sau
## From SQL to DataFrame Pandas import pandas as pd import pyodbc sql_conn = pyodbc.connect['DRIVER={ODBC Driver 13 for SQL Server}; SERVER=SQLSERVER2017; DATABASE=Adventureworks; Trusted_Connection=yes'] query = "SELECT [BusinessEntityID],[FirstName],[LastName], [PostalCode],[City] FROM [Sales].[vSalesPerson]" df = pd.read_sql[query, sql_conn] df.head[3]
bạn sẽ nhận được ba hàng đầu tiên của kết quả
Đảm bảo rằng bạn định cấu hình MÁY CHỦ và CƠ SỞ DỮ LIỆU cũng như thông tin đăng nhập theo nhu cầu của bạn. Nếu bạn đang chạy phiên bản SQL Server cũ hơn, bạn cũng cần phải thay đổi cấu hình trình điều khiển
Chèn dữ liệu từ khung dữ liệu gấu trúc Python vào SQL Server
Khi bạn đã tính toán kết quả bằng Python, sẽ có trường hợp cần chèn lại kết quả vào cơ sở dữ liệu SQL Server. Trong trường hợp này, tôi sẽ sử dụng dữ liệu đã được lưu trữ trong khung dữ liệu Pandas và chỉ cần chèn dữ liệu trở lại SQL Server
Một thẻ đã tồn tại với tên chi nhánh được cung cấp. Nhiều lệnh Git chấp nhận cả tên thẻ và tên nhánh, vì vậy việc tạo nhánh này có thể gây ra hành vi không mong muốn. Bạn có chắc chắn muốn tạo nhánh này không?
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 gói pyodbc trong Python
điều kiện tiên quyết
phạm vi biệt danh=">=sql-server-2017. >=sql-server-linux-ver15"
- Máy chủ SQL cho Windows hoặc cho Linux. biệt danh cuối
phạm vi biệt danh = "= azuresqldb-current"
- Cơ sở dữ liệu Azure SQL. biệt danh cuối
phạm vi biệt danh = "= azuresqldb-mi-current"
Phiên bản được quản lý Azure SQL
SQL Server Management Studio để khôi phục cơ sở dữ liệu mẫu về Azure SQL Managed Instance. . biệt danh cuối
Xưởng dữ liệu Azure. Để cài đặt, hãy xem Tải xuống và cài đặt Azure Data Studio
Làm 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 HumanResources. bảng khoa
USE AdventureWorks; SELECT * FROM HumanResources.Department;
Cài đặt các gói Python
Trong Azure Data Studio, hãy mở một sổ ghi chép mới và kết nối với nhân Python 3
Chọn Quản lý gói
loại hình ảnh = "nội dung" nguồn = ". /media/python-dataframe-sql-server/manage-packages. png" alt-text="Quản lý gói"
Trong ngăn Quản lý gói, chọn tab Thêm mới
Đối với mỗi gói sau, hãy nhập tên gói, nhấp vào Tìm kiếm, sau đó nhấp vào Cài đặt
- pyodbc
- gấu trúc
Tạo tệp CSV mẫu
Sao chép văn bản sau và lưu vào 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 một bảng cơ sở dữ liệu mới
Làm theo các bước trong Kết nối với Máy chủ SQL để kết nối với cơ sở dữ liệu AdventureWorks
Tạo một bảng có tên HumanResources. khoa xét nghiệm. Bảng SQL sẽ được sử dụng để chèn khung dữ liệu
CREATE TABLE [HumanResources].[DepartmentTest][ [DepartmentID] [smallint] NOT NULL, [Name] [dbo].[Name] NOT NULL, [GroupName] [dbo].[Name] NOT NULL ] GO
Tải khung dữ liệu từ tệp CSV
Sử dụng gói Python pandas
để tạo khung dữ liệu, tải tệp CSV, sau đó tải khung dữ liệu vào bảng SQL mới, HumanResources. khoa xét nghiệm
Kết nối với hạt nhân Python 3
Dán mã sau vào một ô mã, cập nhật mã với các giá trị chính xác cho
server
,USE AdventureWorks; SELECT * FROM HumanResources.Department;
0,
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 CSVDepartmentID,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
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[]
Chạy ô
Xác nhận dữ liệu trong cơ sở dữ liệu
Kết nối với nhân SQL và cơ sở dữ liệu AdventureWorks và chạy câu lệnh SQL sau để xác nhận bảng đã được tải thành công với dữ liệu từ khung dữ liệu