如何使用 pyodbc 执行保存在 MS Access 中的查询 [英] How to execute query saved in MS Access using pyodbc

查看:33
本文介绍了如何使用 pyodbc 执行保存在 MS Access 中的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网上有很多关于如何使用 pyodbc 在 MS Access 2007 中运行查询的提示,但所有这些查询都是在 Python 脚本本身中编码的.我想使用 pyodbc 调用已保存在 MS Access 中的查询.我该怎么做?

There are a lot of tips online on how to use pyodbc to run a query in MS Access 2007, but all those queries are coded in the Python script itself. I would like to use pyodbc to call the queries already saved in MS Access. How can I do that?

推荐答案

如果 Access 中保存的查询是一个没有参数的简单 SELECT 查询,那么 Access ODBC 驱动程序将其公开为一个视图,因此您需要做的就是使用查询名称就像它是一个表:

If the saved query in Access is a simple SELECT query with no parameters then the Access ODBC driver exposes it as a View so all you need to do is use the query name just like it was a table:

import pyodbc
connStr = (
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:UsersPublicDatabase1.accdb;"
    )
cnxn = pyodbc.connect(connStr)
sql = """
SELECT * FROM mySavedSelectQueryInAccess
"""
crsr = cnxn.execute(sql)
for row in crsr:
    print(row)
crsr.close()
cnxn.close()

如果查询是某种其他类型的查询(例如,带有参数的 SELECT、INSERT、UPDATE 等),那么 Access ODBC 驱动程序将它们公开为存储过程,因此您需要使用 ODBC {CALL ...} 语法,如

If the query is some other type of query (e.g., SELECT with parameters, INSERT, UPDATE, ...) then the Access ODBC driver exposes them as Stored Procedures so you need to use the ODBC {CALL ...} syntax, as in

import pyodbc
connStr = (
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:UsersPublicDatabase1.accdb;"
    )
cnxn = pyodbc.connect(connStr)
sql = """
{CALL mySavedUpdateQueryInAccess}
"""
crsr = cnxn.execute(sql)
cnxn.commit()
crsr.close()
cnxn.close()

这篇关于如何使用 pyodbc 执行保存在 MS Access 中的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆