How do I import an .accdb file into Python and use the data?

寵の児 提交于 2019-12-02 20:51:50

Say you have a database file named "Database1.accdb" with a table named "Creatures" containing the following data:

CreatureID  Name_EN   Name_JP
----------  --------  -------
         1  Godzilla  ゴジラ
         2  Mothra    モスラ

A minimalist Python script to read the data via pypyodbc on a Windows machine would look something like this:

# -*- coding: utf-8 -*-
import pypyodbc
pypyodbc.lowercase = False
conn = pypyodbc.connect(
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
    r"Dbq=C:\Users\Public\Database1.accdb;")
cur = conn.cursor()
cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures");
while True:
    row = cur.fetchone()
    if row is None:
        break
    print(u"Creature with ID {0} is {1} ({2})".format(
        row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP")))
cur.close()
conn.close()

The resulting output is

Creature with ID 1 is Godzilla (ゴジラ)
Creature with ID 2 is Mothra (モスラ)

Edit

Note that to use the "Microsoft Access Driver (*.mdb, *.accdb)" driver you need to have the Access Database Engine (a.k.a "ACE") installed on your machine. You can check whether you have 32-bit or 64-bit Python by running the following script:

import struct
print("running as {0}-bit".format(struct.calcsize("P") * 8))

Armed with that information you can download and install the matching (32-bit or 64-bit) version of the Access Database Engine from here

Microsoft Access Database Engine 2010 Redistributable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!