Connect Python to MS Access using pyodbc

In this tutorial, you will connect Python to a MS Access using pyodbc.

TLDR solution

connect_msaccess.py
import pyodbc

driver = "Microsoft Access Driver (*.mdb, *.accdb)"
path = "Path-to-access-file"

conn = pyodbc.connect(f"Driver={driver};DBQ={path}/file_name.accdb;")
cursor = conn.cursor()
cursor.execute('SELECT * FROM table_name')
   
for row in cursor.fetchall():
    print(row)

Step-by-Step Example

Step 1: Install the pyodbc Package

If you don't have pyodbc already installed, execute the following command in your terminal:

pip install pyodbc

Step 2: Connect Python to MS Access

Let's say, you have a fish_db.accdb file on your desktop, which contains the following fishes table:

idfish_name
1salmon
2pufferfish
3shark

You can then connect to this database using the following code:

import os
import pyodbc

driver = "Microsoft Access Driver (*.mdb, *.accdb)"
path = os.path.expanduser("~/Desktop")

conn = pyodbc.connect(f"Driver={driver};DBQ={path}/file_name.accdb;")
cursor = conn.cursor()
cursor.execute('SELECT * FROM fishes')
   
for row in cursor.fetchall():
    print(row)

The output of this script should look like this:

(1, 'salmon')
(2, 'pufferfish')
(3, 'shark')

That's it! You just learned how to connect Python to an MS Access database using pyodbc.