Skip to main content
 首页 » 编程设计

python之在 Python 中使用 SQLAlchemy 连接到 Azure 数据库

2025年05月04日21lori

我正在尝试使用 Python 中的 SQLAlchemy 连接到 Azure 数据库。

我的代码如下:

engine_azure = \ 
create_engine('mssql+pyodbc://{Server admin login}:{password}@{Server name}.database.windows.net:1433/{AdventureWorksLT}', echo=True) 

我收到以下消息:

C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\connectors\pyodbc.py:92: SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections 
  "No driver name specified; " 

然后我运行以下代码:

print(engine_azure.table_names()) 

我收到以下消息:

DBAPIError: (pyodbc.Error) ('01S00', '[01S00] [Microsoft][ODBC Driver Manager] Invalid connection string attribute (0) (SQLDriverConnect)') 

请您参考如下方法:

您的连接字符串有 2 个问题:

  1. 根据 SQLAlchemy documentation : 分隔符必须经过 URL 转义 使用传递的精确 pyodbc 字符串时。

  2. 而且您也没有指定 sql 驱动程序名称。

您可以使用下面的代码,它在我这边运行良好:

import pyodbc 
from sqlalchemy import create_engine 
import urllib 
 
params = urllib.parse.quote_plus \ # urllib.parse.quote_plus for python 3 
(r'Driver={ODBC Driver 13 for SQL Server};Server=tcp:yourDBServerName.database.windows.net,1433;Database=dbname;Uid=username@dbserverName;Pwd=xxx;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;') 
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params) 
engine_azure = create_engine(conn_str,echo=True) 
 
print('connection is ok') 
print(engine_azure.table_names()) 

测试结果:

对于连接字符串,您可以通过访问 Azure 门户 -> 您的数据库 -> 连接字符串(在本例中选择 ODBC)来获取它: