SQLAlchemy pytds
SQLAlchemy pytds is a pure Python TDS (Tabular Data Stream) connector for SQLAlchemy, enabling communication with Microsoft SQL Server databases. It provides a DBAPI 2.0 compliant interface implemented entirely in Python, removing external dependencies like FreeTDS or ODBC drivers. The current version is 1.0.2, released on September 14, 2024, indicating active development and maintenance.
Warnings
- breaking SQLAlchemy 2.0 Requirement: `sqlalchemy-pytds` explicitly requires `SQLAlchemy >= 2.0`. Users migrating from applications built with SQLAlchemy 1.x will encounter significant API and behavioral changes, including a new ORM statement paradigm and result object structure. Refer to SQLAlchemy's migration guides for details.
- gotcha Development Status (Beta): The library is classified as 'Development Status :: 4 - Beta' on PyPI. While functional, this indicates it might not be considered fully stable or production-ready for all mission-critical use cases, and APIs could potentially evolve.
- gotcha Encoding Issues (`UnicodeDecodeError`): Users have reported `UnicodeDecodeError` when processing data, especially when integrating with libraries like Pandas or in certain cloud environments. This often stems from character encoding mismatches between the SQL Server, the `python-tds` driver, and Python's default encoding.
- gotcha `RETURNING` Clause Behavior on SQL Server (SQLAlchemy 2.0.9): For a brief period in SQLAlchemy 2.0.9, the `RETURNING` clause for SQL Server was temporarily disabled due to issues with row ordering. It was re-enabled in SQLAlchemy 2.0.10 with special handling. Users on SQLAlchemy 2.0.9 or earlier patch versions might encounter unexpected behavior or errors with `RETURNING`.
- gotcha Bundling/Packaging Issues (e.g., PyInstaller): When creating standalone executables with tools like PyInstaller, the dynamic loading nature of SQLAlchemy dialects can sometimes lead to missing module errors. Explicitly importing `sqlalchemy_pytds` and its underlying driver `python-tds` at a high level in your application might be necessary to ensure they are properly included in the bundle.
Install
-
pip install sqlalchemy-pytds
Imports
- create_engine
from sqlalchemy import create_engine
- sqlalchemy_pytds
import sqlalchemy_pytds
Quickstart
import os
from sqlalchemy import create_engine, text
# Environment variables for connection details
DB_SERVER = os.environ.get('PYTDS_SQLSERVER_HOST', 'localhost')
DB_PORT = os.environ.get('PYTDS_SQLSERVER_PORT', '1433')
DB_USER = os.environ.get('PYTDS_SQLSERVER_USER', 'sa')
DB_PASSWORD = os.environ.get('PYTDS_SQLSERVER_PASSWORD', 'yourStrongPassword123')
DB_NAME = os.environ.get('PYTDS_SQLSERVER_DB', 'master')
# Construct the connection string using the 'mssql+pytds' dialect
connection_string = (
f"mssql+pytds://{DB_USER}:{DB_PASSWORD}@{DB_SERVER}:{DB_PORT}/{DB_NAME}"
)
# Create the engine
try:
engine = create_engine(connection_string, echo=False) # Set echo=True for SQL logging
# Establish a connection and execute a simple query
with engine.connect() as connection:
# Example: Query the SQL Server version
result = connection.execute(text("SELECT @@VERSION AS sql_server_version"))
for row in result:
print(f"Connected to SQL Server Version: {row.sql_server_version}")
print("Successfully connected and queried the database.")
except Exception as e:
print(f"Error connecting to the database: {e}")