MS Access library for python

Question:

Is there a library for using MS Access database in python? The win32 module is not as easy as the MySQL library. Is there a simpler way to use MS Access with Python?

Asked By: Vicky

||

Answers:

Depending on what you want to do, pyodbc might be what you are looking for.

import pyodbc

def mdb_connect(db_file, user='admin', password = '', old_driver=False):
    driver_ver = '*.mdb'
    if not old_driver:
        driver_ver += ', *.accdb'

    odbc_conn_str = ('DRIVER={Microsoft Access Driver (%s)}'
                     ';DBQ=%s;UID=%s;PWD=%s' %
                     (driver_ver, db_file, user, password))

    return pyodbc.connect(odbc_conn_str)

conn = mdb_connect(r'''C:x.mdb''')  # only absolute paths!

Note: you may download the freely-redistributable new-driver, if you don’t have MSOffice installed.

Answered By: stephan

I don’t think win32 is hard. Try use its odbc module. Example of code working with ODBC and PostgreSQL database:

import odbc

def get_pg_ver(db_alias):
    connection = odbc.odbc(db_alias)
    try:
        cursor = connection.cursor()
        cursor.execute('SELECT version()')
        for row in cursor.fetchall():
            print row[0]
    finally:
        connection.close()

get_pg_ver('odbc_name/user/passwd')

This is very similar for every db driver I used in Python and Jython (I work with PostgreSQL, Oracle and Informix).

Answered By: MichaƂ Niklas

I had some recent success using pywin32’s adodbapi module.

The following snippet was taken from this website:

import adodbapi

database = "db1.mdb"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0; Data Source=%s'  % database
tablename = "address"

# connect to the database
conn = adodbapi.connect(constr)

# create a cursor
cur = conn.cursor()

# extract all the data
sql = "select * from %s" % tablename
cur.execute(sql)

# show the result
result = cur.fetchall()
for item in result:
    print item

# close the cursor and connection
cur.close()
conn.close()
Answered By: gdw2

You can use pypyodbc to easily create an empty Access MDB file on win32 platform, and also compact existing Access MDB files.

It can be as easy as:

import pypyodbc
pypyodbc.win_create_mdb( "D:\Your_MDB_file_path.mdb" )

More over, as an dbi 2.0 ODBC library, pypyodbc is highly compatible with pyodbc, you can do SQL database queries like SELECT, INSERT, UPDATE with the library.

Here is the full Tutorial about pypyodbc’s Access support.

Disclaimer: I’m the developer of pypyodbc.

Answered By: pypyodbc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.