简体   繁体   中英

Cannot connect to sql server using pyodbc

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.

You are trying to connect to it from another domain controller then you will get this error when IntegratedSecurity = True , by default

Integrated security means simply - use your windows credentials for login verification to SQL Server. So, if you are logged in to a different domain controller then it will fail. In the case where you are on two different domain controllers then you have no choice but to use IntegratedSecurity = false

So you can try this:

conn = pyodbc.connect(
                      r'DRIVER={SQL Server Native Client 11.0};
                      SERVER=localhost;
                      Integrated_Security=false;
                      Trusted_Connection=yes;
                      UID=user;
                      PWD=password;
                      DATABASE= db')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM