Python-TDS
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
- breaking When connecting to SQL Server 2022 or newer with TDS 8.0 and `Encrypt=strict`, the `TrustServerCertificate` option cannot be set to `true`. Instead, `HostNameInCertificate` must be used for certificate validation.
- gotcha Inserting binary data (e.g., into `VARBINARY` or `IMAGE` columns) requires wrapping the Python bytes object with `pytds.Binary()` to ensure correct type inference by the driver.
- deprecated The NTLM authentication mechanism provided directly through `pytds.login` is deprecated due to its underlying dependency on the `ntlm-auth` package, which is also deprecated.
- gotcha A common 'Permission denied' error occurs during `pip install python-tds` if the user lacks write privileges to system Python directories.
- gotcha When connecting, ensure you correctly use the `server` and `dsn` parameters in `pytds.connect()`. `server` specifies the host, while `dsn` can include both host and instance name (e.g., `hostname\instance_name`).
Install
-
pip install python-tds -
pip install python-tds pyOpenSSL bitarray kerberos
Imports
- pytds
import pytds
Quickstart
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}")