MSSQL Python Driver

1.5.0 · active · verified Wed Apr 15

mssql-python is the official Microsoft Python library for interacting with Microsoft SQL Server, Azure SQL, and SQL databases in Fabric. It provides high-performance data access, bulk copy operations, and Apache Arrow integration. Currently at version 1.5.0, the library maintains an active release cadence with regular enhancements and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Microsoft SQL Server database using `mssql-python`, execute a simple query, create a table, insert data, and fetch results. It highlights the use of environment variables for secure credential management and the recommended `with` statement for connection and cursor management.

import os
import mssql_python

# Ensure the ODBC Driver 18 for SQL Server is installed and configured.
# On Debian/Ubuntu: curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
#                     curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list
#                     sudo apt update
#                     sudo ACCEPT_EULA=Y apt install msodbcsql18
#                     sudo ACCEPT_EULA=Y apt install mssql-tools18
# On macOS: brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
#            brew update
#            ACCEPT_EULA=Y brew install msodbcsql18 mssql-tools18

# Connection details from environment variables (recommended for production)
SERVER = os.environ.get('MSSQL_SERVER', 'localhost')
DATABASE = os.environ.get('MSSQL_DATABASE', 'master')
UID = os.environ.get('MSSQL_USERNAME', '')
PWD = os.environ.get('MSSQL_PASSWORD', '')

# Construct the connection string. Make sure the DRIVER matches your installed ODBC driver.
# For Windows, it might be 'ODBC Driver 17 for SQL Server' or 'SQL Server'.
connection_string = (
    f"DRIVER={{ODBC Driver 18 for SQL Server}}মনের;"
    f"SERVER={SERVER};"
    f"DATABASE={DATABASE};"
) # Omit UID/PWD if using Windows Authentication or EntraID

if UID and PWD:
    connection_string += f"UID={UID};PWD={PWD};"

try:
    with mssql_python.connect(connection_string) as cnxn:
        with cnxn.cursor() as cursor:
            # Execute a simple query
            cursor.execute("SELECT @@SERVERNAME, @@VERSION")
            row = cursor.fetchone()
            if row:
                print(f"Connected to: {row[0]}")
                print(f"SQL Server Version: {row[1]}")

            # Example: Insert data
            cursor.execute("CREATE TABLE IF NOT EXISTS test_table (id INT PRIMARY KEY, name NVARCHAR(50))")
            cnxn.commit()
            print("Table 'test_table' ensured.")

            cursor.execute("INSERT INTO test_table (id, name) VALUES (?, ?)", 1, 'Hello')
            cnxn.commit()
            print("Inserted row (1, 'Hello').")

            # Example: Fetch all data
            cursor.execute("SELECT id, name FROM test_table")
            for row in cursor.fetchall():
                print(f"Fetched: {row}")

except mssql_python.Error as ex:
    sqlstate = ex.args[0]
    print(f"MSSQL Error: {sqlstate} - {ex}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →