how to deal with .mdb access files with python

后端 未结 6 1143
逝去的感伤
逝去的感伤 2020-12-08 00:45

Can someone point me in the right direction on how to open a .mdb file in python? I normally like including some code to start off a discussion, but I don\'t know where to s

6条回答
  •  感动是毒
    2020-12-08 01:09

    Below is some code I wrote for another SO question.
    It requires the 3rd-party pyodbc module.

    This very simple example will connect to a table and export the results to a file.
    Feel free to expand upon your question with any more specific needs you might have.

    import csv, pyodbc
    
    # set up some constants
    MDB = 'c:/path/to/my.mdb'
    DRV = '{Microsoft Access Driver (*.mdb)}'
    PWD = 'pw'
    
    # connect to db
    con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD))
    cur = con.cursor()
    
    # run a query and get the results 
    SQL = 'SELECT * FROM mytable;' # your query goes here
    rows = cur.execute(SQL).fetchall()
    cur.close()
    con.close()
    
    # you could change the mode from 'w' to 'a' (append) for any subsequent queries
    with open('mytable.csv', 'w') as fou:
        csv_writer = csv.writer(fou) # default field-delimiter is ","
        csv_writer.writerows(rows)
    

提交回复
热议问题