pymssql
raw JSON → 2.3.13 verified Tue May 12 auth: no python install: verified quickstart: verified
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.
pip install pymssql Common errors
error ModuleNotFoundError: No module named 'pymssql' ↓
cause The pymssql package is not installed in the Python environment being used, or the Python interpreter cannot locate it due to PATH issues or virtual environment misconfiguration.
fix
Install the package using pip:
pip install pymssql. If using a virtual environment, ensure it is activated. If still failing, check the Python interpreter path in your IDE. error pymssql.OperationalError: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (hostname)\n') ↓
cause The SQL Server is unreachable, not running, or network connectivity issues (e.g., firewall, incorrect hostname/IP, incorrect port, or SQL Server Browser service not running for named instances) are preventing a connection.
fix
Verify the server hostname/IP and port (default 1433), ensure the SQL Server instance is running and configured for remote connections, check firewall rules on both client and server, and ensure the SQL Server Browser service is running if connecting to a named instance. Use
tsql -H <host> -p <port> -U <user> to diagnose FreeTDS connectivity separately. error pymssql.OperationalError: (18456, "Login failed for user 'xxx'.DB-Lib...") ↓
cause The provided username or password for connecting to the SQL Server is incorrect, or the user does not have the necessary permissions to log in to the specified database.
fix
Double-check the username and password in your connection string. Ensure the SQL Server login exists and has permissions for the database. Also, be aware of password length limitations (e.g., historically 30 characters for some pymssql/FreeTDS versions).
error ImportError: DLL load failed: The specified module could not be found. ↓
cause This error typically occurs on Windows when `pymssql` or its underlying FreeTDS dependencies cannot find required DLLs, often due to missing Microsoft Visual C++ Redistributable packages or issues with the FreeTDS library installation.
fix
Ensure the correct Microsoft Visual C++ Redistributable (e.g., 2015-2022) is installed for your system architecture. If installing from source, ensure you have the necessary build tools. Sometimes, using a pre-compiled wheel (
.whl file) downloaded from a reliable source can bypass build issues. error _mssql.c:266:10: fatal error: 'sqlfront.h' file not found ↓
cause This compilation error, common on Linux/macOS, indicates that the FreeTDS development headers (specifically `sqlfront.h`) are missing or not found in the standard include paths when `pymssql` is being installed via pip.
fix
Install the FreeTDS development package for your operating system (e.g.,
sudo apt-get install freetds-dev on Debian/Ubuntu, brew install freetds on macOS). After installing FreeTDS, try reinstalling pymssql again: pip install pymssql. 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()`. ↓
fix Review the official 'Migrating from 1.x to 2.x' documentation. Update connection parameters: `host` becomes `server`. Audit code for removed or changed functions.
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. ↓
fix Explicitly set `tds_version` in `pymssql.connect()` (e.g., `tds_version='7.3'` or `'8.0'`) or configure FreeTDS globally if experiencing connection issues or missing functionality.
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. ↓
fix For SSL/Azure or Kerberos authentication, you may need to install FreeTDS with SSL/Kerberos support on your system and then build `pymssql` from source against it, or use a Docker image that is pre-configured with the necessary FreeTDS libraries. Alternatively, consider using `pyodbc` for Azure SQL Database connections.
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. ↓
fix Ensure you have the correct version of Microsoft C++ Build Tools installed (often part of Visual Studio Community Edition or standalone build tools). Upgrade pip if it's too old to handle `manylinux` wheels.
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. ↓
fix Verify SQL Server configuration (SQL Server Configuration Manager, Surface Area Configuration). Check network firewalls. Use `tsql -H` from FreeTDS to diagnose connectivity issues independently of Python. Ensure `server` and `port` are correctly specified.
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. ↓
fix Always provide explicit aliases for aggregated columns or expressions in your SQL queries (e.g., `SELECT MAX(column_name) AS max_value FROM ...`).
deprecated Python 2 support was officially dropped with `pymssql` version 2.1.5. Newer versions are exclusively for Python 3. ↓
fix Upgrade to Python 3.9 or newer to use current `pymssql` versions. If stuck on Python 2, you must use `pymssql` 2.1.4 or older (which is no longer maintained).
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.04s 26.8M
3.10 alpine (musl) - - 0.04s 26.8M
3.10 slim (glibc) wheel 1.7s 0.03s 26M
3.10 slim (glibc) - - 0.02s 26M
3.11 alpine (musl) wheel - 0.04s 28.5M
3.11 alpine (musl) - - 0.04s 28.5M
3.11 slim (glibc) wheel 1.8s 0.03s 28M
3.11 slim (glibc) - - 0.03s 28M
3.12 alpine (musl) wheel - 0.03s 20.6M
3.12 alpine (musl) - - 0.03s 20.6M
3.12 slim (glibc) wheel 1.6s 0.02s 20M
3.12 slim (glibc) - - 0.02s 20M
3.13 alpine (musl) wheel - 0.03s 20.3M
3.13 alpine (musl) - - 0.02s 20.2M
3.13 slim (glibc) wheel 1.8s 0.02s 20M
3.13 slim (glibc) - - 0.02s 20M
3.9 alpine (musl) wheel - 0.03s 26.3M
3.9 alpine (musl) - - 0.04s 26.3M
3.9 slim (glibc) wheel 2.1s 0.04s 26M
3.9 slim (glibc) - - 0.03s 26M
Imports
- pymssql
import pymssql - _mssql
from pymssql import _mssql
Quickstart verified last tested: 2026-04-24
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}")