SQL Server Connector
Thư viện kết nối SQL Server chuyên dụng cho các tác vụ ETL, được tối ưu hóa cho Pandas, hỗ trợ Tiếng Việt (Unicode) và Upsert (Merge) hiệu năng cao.
Update 0.1.24
-
Về mặt Logic (Coverage): Toàn bộ các "tuyệt chiêu" bạn đã viết như conflict_strategy (sum, last, skip), auto_evolve_schema (tự động thêm cột), hay tự động dò Data Type (_generate_dtype_mapping) đều được giữ nguyên vẹn 100%.
-
Về mặt Transaction (Giao dịch): Ở phiên bản cũ, bạn gộp toàn bộ quá trình: Tạo bảng -> Thêm cột -> Tạo bảng Staging -> Đổ data -> Chạy lệnh MERGE vào chung một giao dịch duy nhất (with self.engine.begin()). Việc này rủi ro ở chỗ: nếu quá trình dài bị đứt kết nối giữa chừng, hoặc thư viện Pandas ngầm commit, toàn bộ sẽ bị kẹt hoặc rollback trong im lặng.
-
Ở phiên bản mới: Chúng ta chuyển sang mô hình Micro-transactions (Giao dịch chia nhỏ) dùng engine.connect() và ép conn.commit() cho từng chặng. Điều này tương thích hoàn hảo với sự khắt khe của SQLAlchemy 2.0+, giúp đảm bảo lệnh nào chạy xong là "chốt sổ" lệnh đó, bất chấp bạn dùng driver pyodbc hay pymssql.
🚀 Tính năng nổi bật
- High Performance: Sử dụng
fast_executemanygiúp insert dữ liệu nhanh gấp 10-50 lần so với thông thường. - Smart Upsert: Tự động chèn mới (Insert) hoặc cập nhật (Update) dựa trên Khóa chính (Primary Key).
- Schema Evolution: Tự động tạo bảng nếu chưa có, tự động thêm cột mới (Add Column) nếu DataFrame có thay đổi.
- Unicode Support: Xử lý triệt để lỗi font chữ Tiếng Việt khi làm việc với SQL Server & Pandas.
- SQLAlchemy 2.0: Tuân thủ chuẩn kết nối hiện đại, an toàn.
📦 Cài đặt
Cách 1: Cài đặt trực tiếp từ Git (Khuyên dùng nội bộ)
Dành cho đồng nghiệp trong team, cài đặt không cần file whl.
# Cài phiên bản mới nhất từ nhánh main
pip install git+https://github.com/johnnyb1509/sqlServerConnector.git
Cách 2: Cài đặt từ file .whl
Dành cho người dùng cuối, cài đặt từ file whl đã build sẵn.
pip install sqlServerConnector
Cấu hình kết nối Database
File cấu hình db_config.yaml
# Thông tin kết nối Database
# Lưu ý: Đảm bảo máy tính đã cài đặt ODBC Driver 17 for SQL Server
db_info:
server: "localhost" # Ví dụ: localhost hoặc
database: "YOUR_DATABASE_NAME" # Ví dụ: TestDB
username: "YOUR_USERNAME" # Ví dụ: sa
password: "YOUR_PASSWORD" # Mật khẩu
📝 Hướng dẫn sử dụng nhanh
- Khởi tạo kết nối
import yaml
from connector import SQLServerConnector
# Load config
with open('config/db_config.yaml', 'r') as f:
conf = yaml.safe_load(f)['db_info']
# Khởi tạo
db = SQLServerConnector(
server=conf['server'],
database=conf['database'],
username=conf['username'],
password=conf['password']
)
- Lấy dữ liệu (Read)
# Cách 1: Lấy toàn bộ bảng
df = db.get_data("SELECT * FROM DM_KhachHang")
# Cách 2: Dùng câu lệnh SQL tuy bien
query = """
SELECT TOP 100 * FROM Sales_Transaction
WHERE created_date >= :from_date
"""
df_sales = db.get_data(query, params={"from_date": "2023-01-01"})
print(df_sales.head())
- Kiểm tra bảng tồn tại
if not db.check_table_exists("Fact_Sales"):
print("Bang Fact_Sales chua ton tai")
- Ghi du lieu (Upsert)
import pandas as pd
# Gia lap du lieu
data = {
'TransactionID': [101, 102],
'Product': ['Laptop Dell', 'Chuot Logitech'], # Ho tro tieng Viet
'Amount': [15000000, 250000]
}
df_new = pd.DataFrame(data)
# Day vao DB
db.upsert_data(
df=df_new,
target_table="Fact_Sales",
match_columns=["TransactionID"], # Khoa so khop (Primary Key)
conflict_strategy="last", # "last" hoac "skip"
auto_evolve_schema=True # Tu dong them cot neu thieu
)
print("Du lieu da duoc upsert thanh cong!")
- Thuc thi cau lenh khong tra ve du lieu
# Vi du: xoa du lieu cu
db.execute_query(
"DELETE FROM Fact_Sales WHERE created_date < :cutoff",
params={"cutoff": "2023-01-01"}
)
- Dong ket noi
# Luon dong ket noi khi hoan tat de giai phong tai nguyen
db.dispose()
⚠️ Lưu ý quan trọng
-
Primary Key: Khi dùng upsert_data, bat buoc phai cung cap
match_columns. Neu bang chua co Primary Key, thu vien se co gang set cac cot nay lam khoa chinh khi tao bang moi. -
Date Time: Các cột ngày tháng nên được convert sang datetime64[ns] trong Pandas trước khi đẩy vào để đảm bảo tính chính xác.
-
Upgrade version: Luôn kiểm tra và cập nhật lên phiên bản mới nhất để tận dụng các tính năng và sửa lỗi mới nhất. For developer, change version in
pyproject.tomland build & upload to PyPI:
python -m build
python -m twine upload dist/*
Metadata
Release files for sqlServerConnector 0.1.24
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| sqlserverconnector-0.1.24.tar.gz | 12.3 kB | Without provenance | Details for sqlserverconnector-0.1.24.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sqlserverconnector-0.1.24-py3-none-any.whl | Python 3 | none | any | Details for sqlserverconnector-0.1.24-py3-none-any.whl |
Total release size: 22.3 kB
Release files / sqlserverconnector-0.1.24.tar.gz
| Download URL | sqlserverconnector-0.1.24.tar.gz |
|---|---|
| Size | 12.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9a24587b4580dbb321c1ba8bfbf2bd8637c08e11898951b72c5d9e83506366d6
|
|
BLAKE2b-256 checksum How to use checksums |
09933dac880078183fc92266f632c8096afe22970ba7e3f96e3c7ce8adcc8d5c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.4
|
Release files / sqlserverconnector-0.1.24-py3-none-any.whl
| Download URL | sqlserverconnector-0.1.24-py3-none-any.whl |
|---|---|
| Size | 10.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
164f87fa00017e63454bcfaea39ad928581115c7fc323b7cafe4d05979c05e44
|
|
BLAKE2b-256 checksum How to use checksums |
50fd733d23d17e5afa24641bfd4deb4ac4a9522098f7ea5f8ffc4910318b2cc6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.4
|
Security for sqlServerConnector 0.1.24
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.