Skip to content

Microsoft SQL (MSSql) via pyodbc

Description:

  • Work with data synchronously in MSSQL

Resources:

This notebook reads its settings from environment variables. Set them before starting Jupyter:

  • MSSQL_HOST: hostname of your Microsoft SQL Server
  • MSSQL_PORT: optional, defaults to 1433
  • MSSQL_USER: SQL Server login
  • MSSQL_PASSWORD: password for that login
  • MSSQL_TRUST_SERVER_CERTIFICATE: optional, defaults to no. Set it to yes only for a test server with a self-signed certificate.

The example uses Microsoft’s ODBC Driver 18 for SQL Server, which must be installed on the machine running Jupyter.

Read data synchronously from an MSSQL database

import os
import pyodbc
# The ODBC drivers installed on this machine
print(pyodbc.drivers())
def mssql_basic():
dsn = (
"DRIVER={ODBC Driver 18 for SQL Server};"
f"SERVER={os.environ['MSSQL_HOST']},{os.environ.get('MSSQL_PORT', '1433')};"
f"UID={os.environ['MSSQL_USER']};PWD={os.environ['MSSQL_PASSWORD']};"
f"TrustServerCertificate={os.environ.get('MSSQL_TRUST_SERVER_CERTIFICATE', 'no')}"
)
cnxn = pyodbc.connect(dsn)
print(f"Connected to database: {cnxn}")
crsr = cnxn.cursor()
rows = crsr.execute("select @@VERSION").fetchall()
print(rows)
crsr.close()
cnxn.close()
mssql_basic()

ganymede is made by Eugo