Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to deal with .mdb access files with python

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 start. I work with mysql a fair bit with python. I was wondering if there is a way to work with .mdb files in a similar way?

like image 318
Richard Avatar asked Sep 01 '10 17:09

Richard


People also ask

Can Python connect to MS Access?

To connect Python to Access: Add the path where you stored the Access file (after the syntax DBQ=). Don't forget to add the MS Access file extension at the end of the path ('accdb') Add the table name within the select statement.

How do I get data from MS Access to Python?

Connect Python to MS Access Database To connect to a database, we need a connection string, basically a text pointer that tells Python where to find the database. For MS Access, we also need to specify the type of ODBC driver (32bit vs 64bit) in the connection string.

How do I fix Access file already in use?

Run Compact and Repair on MS Access Version 2016/2013/2010: Step1: Open and Start Access but not the database file. Step2: Then go to Info >> click Compact and Repair Database. Step3: In the dialog box, navigate to the file you want to repair >> Double Click on it >> Click Ok, repair process starts.


1 Answers

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) 
like image 54
mechanical_meat Avatar answered Oct 03 '22 01:10

mechanical_meat