How to create permanent MS Access Query by Python 3.5.1?

前端 未结 2 1764
小鲜肉
小鲜肉 2021-01-20 23:35

I have about 40 MS Access Databases and have some troubles if need to create or transfer one of MS Access Query (like object) from one db to other dbs. So I tried to solve this

相关标签:
2条回答
  • 2021-01-20 23:57

    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
    
    0 讨论(0)
  • 2021-01-21 00:05

    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

    0 讨论(0)
提交回复
热议问题