76

How do I connect MS SQL Server using Windows Authentication, with the pyodbc library?

I can connect via MS Access and SQL Server Management Studio, but cannot get a working connection ODBC string for Python.

Here's what I've tried (also without 'Trusted_Connection=yes'):

pyodbc.connect('Trusted_Connection=yes',
               driver='{SQL Server}', server='[system_name]',
               database='[databasename]')

pyodbc.connect('Trusted_Connection=yes', uid='me',
               driver='{SQL Server}', server='localhost',
               database='[databasename]')

pyodbc.connect('Trusted_Connection=yes',
               driver='{SQL Server}', server='localhost',
               uid='me', pwd='[windows_pass]', database='[database_name]')

pyodbc.connect('Trusted_Connection=yes',
               driver='{SQL Server}', server='localhost',
               database='[server_name]\\[database_name]')

pyodbc.connect('Trusted_Connection=yes',
               driver='{SQL Server}', server='localhost',
               database='[server_name]\[database_name]')

pyodbc.connect('Trusted_Connection=yes',
               driver='{SQL Server}',
               database='[server_name]\[database_name]')

4 Answers 4

104

You can specify the connection string as one long string that uses semi-colons (;) as the argument separator.

Working example:

import pyodbc
cnxn = pyodbc.connect(r'Driver=SQL Server;Server=.\SQLEXPRESS;Database=myDB;Trusted_Connection=yes;')
cursor = cnxn.cursor()
cursor.execute("SELECT LastName FROM myContacts")
while 1:
    row = cursor.fetchone()
    if not row:
        break
    print(row.LastName)
cnxn.close()

For connection strings with lots of parameters, the following will accomplish the same thing but in a somewhat more readable way:

conn_str = (
    r'Driver=SQL Server;'
    r'Server=.\SQLEXPRESS;'
    r'Database=myDB;'
    r'Trusted_Connection=yes;'
    )
cnxn = pyodbc.connect(conn_str)

(Note that there are no commas between the individual string components.)

5
  • Thanks, that .\ syntax did the trick. Note that: pyodbc.connect('Trusted_Connection=yes', driver='{SQL Server}', server='.\[server_name]', database='[database_name]') also worked. Commented May 13, 2013 at 6:20
  • 1
    how to connect with userid and password Commented Jan 7, 2015 at 16:38
  • This did no work for me. The comment below worked though.
    – CyprUS
    Commented Jun 20, 2016 at 15:23
  • 2
    is there any way to pass a different set of windows auth credentials? e.g. 'Trusted_Connection=yes;UID=blah;PWD=blah'?
    – mdegges
    Commented Sep 28, 2017 at 22:21
  • 8
    @mdegges - Not as such; Microsoft's ODBC driver treats Trusted_Connection and UID/PWD as mutually exclusive. The "preferred" solution on Windows clients would be to run the app as the other user via runas (command line) or [Shift-Right_click] > "Run as different user" (GUI). The corresponding workaround on Linux would be to use the FreeTDS ODBC driver which still supports the older NTLM authentication scheme via the DOMAIN= connection string parameter. Commented Sep 28, 2017 at 22:40
29

Windows Authentication can also be specified using a keyword. Nothing functionally different from the accepted answer, I think it makes code formatting a bit easier:

cnxn = connect(driver='{SQL Server}', server='localhost', database='test',               
               trusted_connection='yes')
2
  • You mention a keyword, yet your string is not using it?
    – Zizzipupp
    Commented Jan 14, 2022 at 16:39
  • trusted_connection is the authentication-related keyword
    – Bryan
    Commented Jan 14, 2022 at 18:09
9

Just wanted to add something as I see the solutions here using localhost; in my experience, SQL Server has issues with this, not sure if its the ODBC driver or the service itse, and prefers the use of (local) if you don't want to specify the local machines name.

cnxn = connect(driver='{SQL Server}', server='(local)', database='test',               
               trusted_connection='yes')
2
  • 3
    This needs to be higher. localhost didn't work for me. (local) did.
    – Denziloe
    Commented Jul 19, 2019 at 12:10
  • 1
    This works for me because I forgot my password and wanted to use windows authentication. Connected successfully from Jupyter Notebook to local sql server Commented Jul 9, 2022 at 18:43
0

HI Use below clode to connect you data & export this data into excel

please use pip command to install dist in command line.

pip install pypyodbc
pip install pandas pip install xlsxwriter pip install requests

CODE__________________

import pypyodbc as odbc 
import pandas as pd
import xlsxwriter
import requests
import datetime

conn_str = (
    r'Driver=SQL Server;'
    r'Server=AJAYZORI\SQLEXPRESS;'
    r'Database=Production;'
    r'Trusted_Connection=yes;'
    )

try:
    conn =  odbc.connect(conn_str)
except:
    print("Error")
    exit()


try:
    with conn.cursor() as cursor:
        # Read data from database
        sql = "SELECT * FROM MAT_LISTING_MUMBAI_DATABASE_TBL"
        cursor.execute(sql)

        # Fetch all rows

        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        #print(rows[0])
        # Print results
        #for row in rows:
        #    print(row)
        
        df = pd.DataFrame(list(rows), columns=columns)
        now = datetime.datetime.now()
        print(now)
        writer = pd.ExcelWriter( now.strftime("%B  %G HH_%I MM_%M  SS_%S %p") + " Output.xlsx", engine="xlsxwriter",)
        df.to_excel(writer, sheet_name='data')
        writer.close()

finally:
    conn.close()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.