Python – Cannot connect to sql server using pyodbc

databasepyodbcpythonsqlsql server

I'm unable to connect to SQL-server using pyodbc module in python, my connection string is like this.

pyodbc.connect(driver=driv,host=server,database=db,trusted_connection="yes",user=user,password=pasw)

I'm hitting an error like this

Error: ('28000', '[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (18452) (SQLDriverConnect); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (18452)')

The version of sql server I'm having is,

Microsoft SQL Server 2012 (SP1) – 11.0.3000.0 (X64) Oct 19 2012
13:38:57 Copyright (c) Microsoft Corporation Standard Edition
(64-bit) on Windows NT 6.2 (Build 9200: )

which I had got by running SELECT @@VERSION query.
I had used SQL Server Native Client 11.0 as driver. One thing I noticed is that in sql server management studio I used SQL server authentication instead of windows authentication. But here, by the error message it seems it is trying windows authentication instead. Is there any way I can use SQL server authentication instead of windows authentication here? I guess that would solve this problem.

Best Answer

With the more recent versions of Microsoft's ODBC driver for SQL Server, Trusted_Connection=yes takes precedence, so the connection will attempt to use Windows authentication even if UID= and PWD= are supplied. If you want to use SQL Server authentication then simply use Trusted_Connection=no and supply the UID= and PWD= for the SQL Server login.