Python-TDS

1.17.1 · active · verified Fri Apr 10

Python-TDS is a pure Python DBAPI driver for Microsoft SQL Server, implementing the Tabular Data Stream (TDS) protocol. This cross-platform library eliminates dependencies on ADO or FreeTDS, offering features like MARS, bulk insert, table-valued parameters, and TLS/Kerberos support. The current version is 1.17.1, with active development and consistent releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Microsoft SQL Server database using `python-tds`, execute a simple query, and fetch results. It uses environment variables for connection details for security and flexibility. The connection and cursor objects are managed using Python's `with` statement for automatic resource cleanup.

import os
import pytds

# --- Environment Variables (Replace with your actual values or secure fetching) ---
SERVER = os.environ.get('SQL_SERVER', 'your_server.database.windows.net')
DATABASE = os.environ.get('SQL_DATABASE', 'your_database')
USER = os.environ.get('SQL_USER', 'your_username')
PASSWORD = os.environ.get('SQL_PASSWORD', 'your_password')

try:
    # Establish a connection using a context manager
    with pytds.connect(server=SERVER, database=DATABASE, user=USER, password=PASSWORD) as conn:
        print("Successfully connected to the database!")

        # Create a cursor object using a context manager
        with conn.cursor() as cursor:
            # Execute a simple query
            cursor.execute("SELECT 1 AS ConnectionTest")

            # Fetch the result
            result = cursor.fetchone()
            print(f"Query result: {result}")

            # Example: Fetch all results
            cursor.execute("SELECT 'Hello from Python-TDS' AS Message")
            all_results = cursor.fetchall()
            print(f"All results: {all_results}")

except pytds.Error as e:
    print(f"Database error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →