在 Python 中使用 MySQLdb 进行 Windows 身份验证

问题描述:

有没有办法在 Python 中使用 Windows 身份验证连接到 MySQL 数据库?它在 MySQL 服务器上启用,我使用 Microsoft MySQL Server Management Studio 登录它没问题.但是,通常的设置:

Is there a way to connect to MySQL database with Windows Authentication in Python? It is enabled on MySQL server, I login into it with Microsoft MySQL Server Management Studio no problem. However, usual setup:

import MySQLdb
db = MySQLdb.connect(host="sampleserver\\demo",
                      db="sample") 

似乎不起作用.事实上,主机甚至不被识别.除了该主机之外,我们的 DBA 没有给我一个端点.它适用于管理工作室.

doesnt seem to work. In fact, host is not even recognized. Our DBA didnt give me a endpoint aside from that host. It works for the Management Studio.

编辑 1

根据答案中的建议,尝试使用 pyodbc 库连接字符串方法.

As per suggestion in the answer, tried connecting with the connection string method with pyodbc library.

import pyodbc
cnxn = pyodbc.connect("DRIVER={SQL Server};"
                      "SERVER=server_name\\demo;"
                      "DATABASE=sample;"
                      "UID=auth_windows")

双反斜杠,我正在转义服务器名称中的反斜杠

Double backslash, I'm escaping the backsalsh in the server name

收到相当长的错误消息:

Getting fairly long error message:

Error: ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'auth_windows'. (18456) (SQLDriverConnect); 
[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'auth_windows'. (18456)")

当我尝试添加 IntegratedSecurity=yes 时,我也得到:

When I tried to add IntegratedSecurity=yes, I also get:

[01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)

基于 Jaco 的回答,但是 pyodbc 库需要稍微不同的字符串,否则会产生无法识别的属性错误:

Based on Jaco's answer but pyodbc library requires slightly different string, or it will produce unrecognized attribute error:

Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Uid=auth_window;