All Snippets

Test SQL Server Connection Using Python and pyodbc

Connect to Microsoft SQL Server from Python using pyodbc and ODBC Driver 18, with Windows authentication, encryption, and a simple connection test.

This snippet uses ODBC Driver 18 for SQL Server by default. If you have ODBC Driver 17 installed instead, change ODBC Driver 18 for SQL Server to ODBC Driver 17 for SQL Server in the connection string.

A simple Python script to test connectivity to a Microsoft SQL Server database using pyodbc and ODBC Driver 18 for SQL Server.

This example uses Windows authentication (Trusted_Connection=yes), enables encryption, and verifies the connection by returning the current database and SQL Server user.

Prerequisites

Install pyodbc:

bash
1
pip install pyodbc

You also need Microsoft ODBC Driver 18 for SQL Server installed on the machine running the script.

Script

python
1
import pyodbc
2
 
3
SERVER = "your-server-name"
4
DATABASE = "your-database-name"
5
 
6
connection_string = (
7
    "DRIVER={ODBC Driver 18 for SQL Server};"
8
    f"SERVER={SERVER};"
9
    f"DATABASE={DATABASE};"
10
    "Trusted_Connection=yes;"
11
    "Encrypt=yes;"
12
    "TrustServerCertificate=yes;"
13
    "Connection Timeout=10;"
14
)
15
 
16
try:
17
    print("Connecting...")
18
 
19
    conn = pyodbc.connect(connection_string)
20
 
21
    print("✅ Connection successful!")
22
 
23
    cursor = conn.cursor()
24
    cursor.execute("SELECT DB_NAME(), SUSER_SNAME()")
25
 
26
    database, user = cursor.fetchone()
27
 
28
    print(f"Database: {database}")
29
    print(f"Connected user: {user}")
30
 
31
    cursor.close()
32
    conn.close()
33
 
34
except pyodbc.Error as e:
35
    print("❌ Connection failed:")
36
    print(e)

Configuration

Replace these values with your SQL Server details:

python
1
SERVER = "your-server-name"
2
DATABASE = "your-database-name"

For a named SQL Server instance:

python
1
SERVER = "server-name\\instance-name"

For a specific port:

python
1
SERVER = "server-name,1433"

Connection Settings

SettingDescription
Trusted_Connection=yesUses Windows authentication
Encrypt=yesEnables encryption for the SQL Server connection
TrustServerCertificate=yesTrusts the server certificate without validating its certificate chain
Connection Timeout=10Sets the connection timeout to 10 seconds

Verify the Connection

The script executes:

sql
1
SELECT DB_NAME(), SUSER_SNAME()

This returns the database name and SQL Server user associated with the current connection.

Example output:

text
1
Connecting...
2
✅ Connection successful!
3
Database: MyDatabase
4
Connected user: DOMAIN\username

Troubleshooting

If the connection fails, check the following:

  1. SQL Server is running and accessible from the machine running the script.
  1. The server and database names are correct.
  1. The required ODBC Driver version is installed.
  1. Your Windows account has permission to access the database.
  1. The SQL Server firewall allows the required port.
  1. TCP/IP is enabled for SQL Server if connecting remotely.

TrustServerCertificate=yes is convenient for testing and internal environments, but for production systems it is generally better to configure a properly trusted SQL Server certificate and validate the certificate chain.