Prox
Prox

Reputation: 759

How do I log into MSSQL using Windows Auth on Python?

I have tried both pypyodbc and pymssql with no luck using Windows Authentication. Any ideas? I can log in when I use both the username and password but I do not want to do this. I want to use Windows Auth.

I actually have only been able to get pypyodbc working. I get different connection errors with pymssql. I have Googled different examples and they are not working. I figure I am not using the correct format for username or something. Do I have to put "DomainName\myusername" in there instead of just my username? I have tried this with no luck.

How could I convert this to Windows Auth login?

import pypyodbc
connection = pypyodbc.connect('Driver={SQL Server};'
                                'Server=IPaddresshere;'
                                'Database=PythonTest;'
                                'uid=myuser;pwd=mypass')

cursor = connection.cursor() 
SQLCommand = ("SELECT FirstName, LastName, UID "      
    "FROM dbo.member "
    "WHERE UID = ?")
Values = [2]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
# note: UID column is an integer.  You can't normally take an integer and place it in a string.
# so you must add str(results[2])
print("Employee " + results[0] + " " + results[1] + " ID is " + str(results[2]))
connection.close()

Upvotes: 2

Views: 13424

Answers (2)

NicoRiff
NicoRiff

Reputation: 4883

Try setting Trusted Connection:

pyodbc.connect(r'Driver={SQL Server};Server=DBINSTANCE;Database=myDB;Trusted_Connection=yes;')

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26856

In the case when you want to use Windows authentication, your connection string should look like:

Driver={SQL Server};'
'Server=IPaddresshere;'
'Database=PythonTest;'
'Trusted_Connection=True;'

Upvotes: 5

Related Questions