Registry / database / pymssql

pymssql

JSON →
library2.3.13pypypi✓ verified 29d ago

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
INSTALL
IMPORT
SIG · PYMSSQL
P
pymssql
databasepythonv2.3.13
Install
1.8s avg
Import
29ms
Disk
24MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v2.3.13 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.030s · 26.8MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 1.8s · import 0.028s · 26MB
24MB installed
● package 24MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pymssql
✓ import pymssql
This is the primary DB-API compliant module for general use.
_mssql
✓ from pymssql import _mssql
A lower-level module offering potentially better performance and more direct control, but less DB-API compliant.

This quickstart demonstrates how to establish a connection to a SQL Server database, execute a simple query, and fetch results using the `pymssql` module. It uses environment variables for credentials, which is a recommended practice for security. Results are fetched as dictionaries for easier access.

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}")
Debug
Known issues
breakingMigration 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.
affects: All 2.x versions when migrating from 1.x
gotchaDefault 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.
affects: 2.1.4 and newer
gotchaThe 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.
affects: All 2.x versions using official wheels
gotchaOn 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.
affects: All versions, when installing from source on Windows
gotchaConnection 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.
affects: All versions
gotchaWhen 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 ...`).
affects: All 2.x versions using `as_dict=True`
deprecatedPython 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).
affects: 2.1.5 and newer
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pymssql'
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.
pymssql.OperationalError: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (hostname)\n')
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.
pymssql.OperationalError: (18456, "Login failed for user 'xxx'.DB-Lib...")
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).
ImportError: DLL load failed: The specified module could not be found.
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.
_mssql.c:266:10: fatal error: 'sqlfront.h' file not found
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`.
Upgrade
Version history
2.3.13latest on PyPI · released Feb 14, 2026
Audit
Dependencies
FreeTDSoptionalpymssql builds on FreeTDS. Official wheels bundle a static copy, but for source builds, specific FreeTDS features (like SSL/Kerberos), or certain environments (e.g., Azure), a system-installed FreeTDS (v1.2.18+ recommended, though v0.95+ was previously sufficient for some features) might be required or preferred.
CythonoptionalRequired for building pymssql from source (e.g., when wheels are not available for your platform/Python version). Specifically requires Cython > 3.0.10 for recent pymssql versions.
Agent activity
20 hits · last 30 days
node
18
Resources