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 comment