使用 pyODBC 连接到 ODBC

jen*_*ryb 4 python ms-access odbc dsn pyodbc

我已经阅读了 python odbc 库中的所有常见问题解答页面以及其他示例,并使用以下代码设法连接到了 DSN:

cnxn = pyodbc.connect("DSN=DSNNAME")
cursor = cnxn.cursor()
cursor.tables()
rows = cursor.fetchall()
for row in rows:
    print row.table_name
Run Code Online (Sandbox Code Playgroud)

但对于其他一切,我不断收到此错误:

Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过以下步骤使用 Microsoft Access 提取我的数据:创建新数据库,单击外部数据选项卡,单击更多并选择 ODBC 数据库,通过创建链接表使用数据源链接,在选择数据源窗口中选择机器数据源并选择具有系统类型的 NAME2,按确定并选择表 acr.Table_one_hh,然后选择表中我想查看的字段,如城市、州、国家、地区等。当我将鼠标悬停在表名称上时,它会显示 DSN 名称、描述、可信连接 = 是、APP、数据库名称和表名称。

我尝试了两种方法,首先

cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=mycomputername;DATABASE=mydatabase;Trusted_Connection=yes;')
cursor = cnxn.cursor()
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误:

Error: ('08001', '[08001] [Microsoft][SQL Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [2].  (2) (SQLDriverConnect); [HYT00] [Microsoft][SQL Server Native Client 10.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (2)')
Run Code Online (Sandbox Code Playgroud)

我试过

cnxn = pyodbc.connect("DSN=DSNNAME, DATABASE=mydatabase")
cursor = cnxn.cursor()
cursor.execute("""SELECT 1 AS "test column1" from acr.Table_one_hh""")
cursor.tables()
rows = cursor.fetchall()
for row in rows:
    print row.table_name
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误

Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Run Code Online (Sandbox Code Playgroud)

jen*_*ryb 8

我设法解决了我的问题。我的代码并没有真正改变。

cnxn = pyodbc.connect("DSN=BCTHEAT")
cursor = cnxn.cursor()
cursor.execute("select * from acr.Table_one_hh")
row = cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

然后我将结果写入一个 csv 文件。