Skip to main content
 首页 » 编程设计

python之使用 pyodbc 导致错误 : Data source name not found and no default driver specified

2024年10月24日7sxdcgaq8080

我正在使用 pyodbc 连接 SQL Server。我创建了这样的连接字符串:

from sqlalchemy import Table, Column, databases, Integer, String, ForeignKey, create_engine 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import session 
engine = create_engine('mssql+pyodbc://sa:123@localhost/TrainQuizDB') 
engine.connect() 

TrainQuizDB 是我在 Sql Server 中创建的数据库名称。

有关更多信息,我有 windows 8.1 64 位,我安装了 python 版本 3.5.1 32 位,我从 http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyodbc 下载了 pyodbc。 (pyodbc-3.0.10-cp35-none-win32.whl)。 但是当我尝试连接时会导致此错误:

sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') 

我还测试了 ODBC 数据源中的连接,它是成功的。

请您参考如下方法:

如 relevant section of the SQLAlchemy documentation 中所述:

Hostname-based connections are not preferred, however are supported. The ODBC driver name must be explicitly specified

因此,您需要将驱动程序名称添加到您的连接字符串中:

engine = create_engine('mssql+pyodbc://sa:123@localhost/TrainQuizDB?driver=ODBC+Driver+17+for+SQL+Server')