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

时间:2019-04-25 18:23:51

标签: python mysql sql pyodbc

我在通过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)')

2 个答案:

答案 0 :(得分:0)

尝试如下

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 Server编写并分发了多个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

答案 1 :(得分:0)

用于SQL Server的ODBC驱动程序17 是您需要使用的标准驱动程序。它涵盖了大多数用例。 如果执行以下操作,它将列出您要在其上运行的计算机上所有可用的驱动程序。

pyodbc.drivers()

如果用于SQL Server的ODBC驱动程序17 不在列表中,则需要通过从Microsoft网站下载进行安装。