Python – PyODBC – Microsoft Access : Simple script


Here’s a simple python script showing how to access MDB (Microsoft Access) database

import os
import pyodbc

dataFile = "Northwind.mdb"
databaseFile  = os.getcwd() + "\\" + dataFile
connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s" % databaseFile
dbConnection   = pyodbc.connect(connectionString)
cursor = dbConnection.cursor()
cursor.execute("select top 5 * from Suppliers")
rows = cursor.fetchall()
for row in rows:
    print row.CompanyName

take a look at the script below to get column names, column type and width

import os
import pyodbc

dataFile = "Northwind.mdb"
databaseFile  = os.getcwd() + "\\" + dataFile
connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s" % databaseFile
dbConnection   = pyodbc.connect(connectionString)
cursor = dbConnection.cursor()

for row in cursor.columns(table='Suppliers'):
    print "Field name: " + str(row.column_name)
    print "Type: " + str(row.type_name)
    print "Width: " + str(row.column_size)

One thought on “Python – PyODBC – Microsoft Access : Simple script

  1. nice site!! is there a good example of executemany in python to insert data in to access tables? Mike

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s