连接到 SQL 服务器抛出 pyodbc.InterfaceError

Connecting to SQL Server throws pyodbc.InterfaceError

我尝试从 Python 代码连接到 Azure 云上的 MS-SQL 数据库,如下所示。

import pyodbc 
connect_str = "Driver={ODBC Driver 17 for SQL Server};" + \
    "Server={server},1433;".format(server='tcp:ipaddress.database.windows.net') + \
    "Database={database};".format(database='mydb') + \
    "uid={uid};".format(uid='myuserid') + \
    "pwd={pwd};".format(pwd='secretpswd') + \
    "Encrypt=yes;TrustServerCertificate=no;"
cnxn = pyodbc.connect(connect_str)

我收到错误:

pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'myuserid'. (18456) (SQLDriverConnect)")

我尝试从连接字符串中的服务器定义中删除端口号。我也尝试过不选择 Encrypt 和 TrustServerCertificate。一直显示相同的错误。

我尝试使用 Management Studio 使用相同的凭据进行连接并且成功了。

你能指出我做错了什么吗?

好的,我设法找出问题所在。

我的密码包含一些未正确转义的值。

首先,如果连接字符串选项的值包含“;”它应该用花括号转义。

所以我需要更换:

"pwd={pwd};".format(pwd='secretpswd')-字符串pwd=secretpswd

"pwd={{{pwd}}};".format(pwd='secretpswd') - 字符串 pwd={secretpswd}

此外,如果密码包含任何花括号,则应将其加倍。可以这样

pwd = 'password_with_curly_braces_{}'
pwd = pwd.replace('}', '}}').replace('{', '{{')