pymssql
pymssql is a Python DB-API (PEP-249) interface to Microsoft SQL Server, built on top of FreeTDS. The 2.x branch, a complete rewrite using Cython, offers improved performance and Python 3 compatibility. It is actively maintained with regular releases, currently at version 2.3.13, and supports Python 3.9 and newer.
Warnings
- breaking Migration from pymssql 1.x to 2.x involves significant API changes. Version 2.0.0 was a complete rewrite in Cython, dropping Python 2.6 support and introducing incompatible changes such as the removal of the `dsn` parameter and the renaming of `host` to `server` in `pymssql.connect()`.
- gotcha Default TDS protocol version changed. Starting with pymssql 2.1.4, the default TDS protocol version is no longer '7.1' (it became `None` in 2.2.0), requiring explicit specification via the `tds_version` parameter in `pymssql.connect()` or `_mssql.connect()`, a `TDSVER` environment variable, or `freetds.conf` for certain SQL Server versions or features. Using an unsupported TDS version for your FreeTDS library can lead to unexpected behavior.
- gotcha The statically-linked FreeTDS bundled with official `pymssql` wheels for Linux and Windows might lack SSL and Kerberos support. This can prevent connections to Azure SQL Database or domain logins to SQL Server instances that require these features.
- gotcha On Windows, if pre-built wheels are not available or fail, installing `pymssql` from source requires Microsoft C++ Build Tools (e.g., Visual C++ 14.0 or newer), which can be a common installation hurdle.
- gotcha Connection failures are often due to SQL Server configuration (e.g., remote connections disabled, specific protocols not enabled, or firewall blocking the connection) rather than `pymssql` itself. Issues with `freetds.conf` (if used) can also cause problems.
- gotcha When fetching rows as dictionaries using `cursor(as_dict=True)`, aggregated columns or expressions without explicit aliases (e.g., `SELECT MAX(column_name) FROM ...`) may result in the column being omitted from the dictionary, as `pymssql` cannot determine a suitable dictionary key.
- deprecated Python 2 support was officially dropped with `pymssql` version 2.1.5. Newer versions are exclusively for Python 3.
Install
-
pip install pymssql
Imports
- pymssql
import pymssql
- _mssql
from pymssql import _mssql
Quickstart
import pymssql
import os
# Environment variables are recommended for sensitive credentials
SERVER = os.environ.get('PYMSSQL_SERVER', 'your_server.database.windows.net')
USER = os.environ.get('PYMSSQL_USER', 'your_username')
PASSWORD = os.environ.get('PYMSSQL_PASSWORD', 'your_password')
DATABASE = os.environ.get('PYMSSQL_DATABASE', 'your_database')
try:
# Establish connection using a context manager
with pymssql.connect(server=SERVER, user=USER, password=PASSWORD, database=DATABASE) as conn:
print("Successfully connected to SQL Server!")
# Create a cursor, with results returned as dictionaries
with conn.cursor(as_dict=True) as cursor:
# Execute a query
cursor.execute('SELECT @@VERSION as server_version, GETDATE() as current_time')
# Fetch one row and print it
row = cursor.fetchone()
if row:
print(f"Server Version: {row['server_version']}")
print(f"Current Server Time: {row['current_time']}")
# Example: Insert data (if autocommit is False, call conn.commit())
# cursor.execute("INSERT INTO YourTable (Col1, Col2) VALUES (%s, %s)", ('value1', 123))
# conn.commit()
except pymssql.OperationalError as e:
print(f"Connection failed: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")