python pyodbc : how to connect to a specific instance

Authentication

First, you're providing both uid/pwd (SQL Server authentication) and trusted_connection (Windows authentication). Pick one, you can't use both. I'll assume SQL Server authentication for the following examples.

Connection strings

Connecting to named instance instance1 using the instance name:

connSqlServer = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=192.106.0.102\instance1;DATABASE=master;UID=sql2008;PWD=password123')

Connecting to named instance using TCP/IP using the port number 1443:

connSqlServer = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=192.106.0.102,1443;DATABASE=master;UID=sql2008;PWD=password123')

Keyword alternative

pyodbc.connect() supports keywords, I think these are easier to read and you don't have to do any string formatting if you're using variables for connection string attributes:

Named instance:

connSqlServer = pyodbc.connect(driver='{SQL Server Native Client 10.0}',
                               server='192.106.0.102\instance1',
                               database='master',
                               uid='sql2008',pwd='password123')

TCP/IP port:

connSqlServer = pyodbc.connect(driver='{SQL Server Native Client 10.0}',
                               server='192.106.0.102,1443',
                               database='master',
                               uid='sql2008',pwd='password123')

Tags:

Python

Sql

Pyodbc