通过 pyodbc 连接 python 和 SQL 时出现问题(未指定默认驱动程序)

Having problem connecting python and SQL through pyodbc (no default driver specified)

我在通过 pyodbc 连接 SQL 和 python 时遇到问题。

我已经尝试了系统中的大部分驱动程序名称和内含物,但我仍然遇到同样的问题。

代码:

import pyodbc 
conn = pyodbc.connect(
    "Driver='{SQL Server Native Client 11.0}';"              
               "Server = server;"
               "Database = db;"
               "username = xxx;"
               "password = xxxxxxxxx;"
               "Trusted_Connection = yes;")




cursor = conn.cursor()
cursor.execute('SELECT * FROM db.table')

for row in cursor:
    print(row)

错误:

InterfaceError                            Traceback (most recent call last)
<ipython-input-36-04dae4d66996> in <module>()
      1 import pyodbc
      2 conn = pyodbc.connect(
----> 3     "Driver='{SQL Server Native Client 11.0}';"
      4                "Server = server;"
      5                "Database = db;"

InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

像下面这样尝试

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=test;DATABASE=test;UID=user;PWD=password')

 --DRIVER={ODBC Driver 17 for SQL Server} here driver name should be yours odbc version

no need --Trusted_Connection=True when you are providing user name and password

Microsoft 已经为 SQL 服务器编写并分发了多个 ODBC 驱动程序:

{SQL Server} - released with SQL Server 2000
{SQL Native Client} - released with SQL Server 2005 (also known as version 9.0)
{SQL Server Native Client 10.0} - released with SQL Server 2008
{SQL Server Native Client 11.0} - released with SQL Server 2012
{ODBC Driver 11 for SQL Server} - supports SQL Server 2005 through 2014
{ODBC Driver 13 for SQL Server} - supports SQL Server 2005 through 2016
{ODBC Driver 13.1 for SQL Server} - supports SQL Server 2008 through 2016
{ODBC Driver 17 for SQL Server} - supports SQL Server 2008 through 2017

ODBC Driver 17 for SQL Server 是您需要使用的标准驱动程序。它涵盖了大多数用例。 如果你执行下面的命令,它会列出你正在尝试 运行 来自的机器上所有可用的驱动程序。

pyodbc.drivers()

如果 SQL 服务器 ODBC 驱动程序 17 不在列表中,您需要从 Microsoft 站点下载安装它。