How to create permanent MS Access Query by Python 3.5.1?

非 Y 不嫁゛ 提交于 2019-12-01 21:42:10

You can use a CREATE VIEW statement to create a saved Select Query in Access. The pyodbc equivalent to your VBA example would be

crsr = conn.cursor()
sql = """\
CREATE VIEW TestQuery AS
SELECT * FROM TestTable
"""
crsr.execute(sql)

To delete that saved query you could simply execute a DROP VIEW statement.

For more information on DDL in Access see

Data Definition Language

Consider the Python equivalent of the VBA running exactly what VBA uses: a COM interface to the Access Object library. With Python's win32com third-party module, you can call the CreateQueryDef method. Do note: this COM interfacing can be applied in other languages such as PHP and R!

Below uses a try/except/finally block to ensure the Access application process closes regardless of error or success of code (similar to VBA's On Error handling):

import win32com.client

# OPEN ACCESS APP AND DATABASE
dbases = ["..\Test #1.accdb", "..\Test #2.accdb", "..\Test #3.accdb", "..\Test #4.accdb"]

try:
    oApp = win32com.client.Dispatch("Access.Application")

    # CREATE QUERYDEF
    for db in dbases:
        oApp.OpenCurrentDatabase(db)
        currentdb = oApp.CurrentDb()
        currentdb.CreateQueryDef("TestQuery", "SELECT * FROM TestTable")
        currentdb = None
        oApp.DoCmd.CloseDatabase

except Exception as e:
    print(e)

finally:
    currentdb = None
    oApp.Quit
    oApp = None

Also, if you need to run DML statements via pyodbc and not a COM interface, consider distributed queries as Access can query other databases directly in SQL. Below should work in Python (be sure to escape the backslash):

SELECT t.* FROM [C:\Path\To\Other\Database.accdb].TestTable t
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!