Python pyodbc 使用 SQL 服务器身份验证连接到 Sql 服务器

Python pyodbc connect to Sql Server using SQL Server Authentication

window 用户详细信息与我登录的 Sql 服务器用户不同。所以我尝试使用用户名 (Admin_JJack) 和 pyodbc 连接到数据库密码。但是 Window User(Jack) 的连接显示失败,我不知道哪里出了问题。

我的连接字符串:

connection = pyodbc.connect(
    "Driver={"SQL Driver"};"
    "Server= "ServerName";"
    "Database="DatabaseName";"
    "UID="UserName";"
    "PWD="Password";"
    "Trusted_Connection=yes"
)

pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'Jack'. (18456) (SQLDriverConnect);

如何使用sql服务器身份验证连接到数据库?

当您使用 "Trusted_Connection=yes" 时,UID 和 PWD 密钥都会被忽略,并且 Windows 帐户用于身份验证。

如果您想使用 UID 和 PWD 值而不是 Windows NTLM 帐户进行身份验证,您必须使用 "Trusted_Connection=No" 或从连接字符串中删除此选项。

Trusted_Connection

Specifies whether a user connects through a user account by using either Kerberos [RFC4120] or another platform-specific authentication as specified by the fIntSecurity field (for details, see [MS-TDS] section 2.2.6.4).

The valid values are "Yes", "1", or empty string, which are equivalent, or "No". If the value "No" is not specified, the value "Yes" is used.

If the value is "No", the UID and PWD keys have to be used to establish a connection with the data source.

If the DSN key and the UID key are not included in the connection string or if the value of the UID key is an empty string, the value of the Trusted_Connection key has to be "Yes". If the Trusted_Connection key is not specified in the connection string, the value has to be obtained from the contents of the settings in the DSN key. If the Trusted_Connection key is not specified in DSN or if the given DSN does not exist, the default value is "No".

If the value of the Trusted_Connection key is "Yes", both the UID and PWD keys are ignored. Otherwise, the UID key has to be specified.

In Microsoft implementations, this user account is a Windows user account and NTLM authentication [MSDN-NTLM] is used when the value of the Trusted_Connection key is "Yes".

来源:https://msdn.microsoft.com/

slightly different syntax:

conn = pyodbc.connect('Driver={SQL Server};'
                        'Server=dbServer1;'
                        'Database=db1;'
                        'UID=user1;'
                        'PWD=uSer1Pass!;'
                        'Trusted_Connection=no;')

对于 windows 身份验证,您需要输入 Trusted_Connection=yes;而不是 uid 和 pwd,如果这不起作用,请尝试 DSN 方法 (https://docs.microsoft.com/en-us/sql/integration-services/import-export-data/connect-to-an-odbc-data-source-sql-server-import-and-export-wizard?view=sql-server-ver15) 我建议使用选项 1,但这是你的决定