SQLAlchemy pytds

1.0.2 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a Microsoft SQL Server database using `sqlalchemy-pytds` and `SQLAlchemy`'s `create_engine` function. It retrieves connection parameters from environment variables or uses defaults, then executes a simple query to verify the connection.

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}")

view raw JSON →