pymssql

2.3.13 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

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}")

view raw JSON →