简体   繁体   中英

How do you create a mdb database file in Python?

I would like to create a mdb database file in windows with Python and can't seem to figure it out with the Python Docs. Everything I read about is related to making a connection and what to do with the cursor.

Any thoughts? Thanks...

My experience with the comtypes module has been fairly good. You'll probably want to have an Access DAO/ADO/VBA reference handy for the methods that are used, however, as the comtypes module generates COM library wrappers dynamically, so there's no built-in documentation.

Here's a brief example of how it works. (Go ahead and test it out yourself.)

from comtypes.client import CreateObject

access = CreateObject('Access.Application')

from comtypes.gen import Access

DBEngine = access.DBEngine
db = DBEngine.CreateDatabase('test.mdb', Access.DB_LANG_GENERAL)
      # For me, test.mdb was created in my My Documents folder when I ran the script 

db.BeginTrans()

db.Execute("CREATE TABLE test (ID Text, numapples Integer)")
db.Execute("INSERT INTO test VALUES ('ABC', 3)")

db.CommitTrans()
db.Close()

(Moved the second import statement after the CreateObject line for cases where the Python wrapper module for the typelibrary didn't previously exist.)

First download and install Microsoft Access Database Engine 2010 Redistributable if you haven't.

Then you should install pyodbc module.

Now you can connect to access database :

ConFileName=(r'c:\mydb\myaccess.mdb')
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + ConFileName + ';')
cursor = conn.cursor()

To select from any table in the database please use this simple code :

ConFileName=(r'c:\mydb\myaccess.mdb')
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + ConFileName + ';')
cursor = conn.cursor()
cursor.execute('select * from table1')
for row in cursor.fetchall():
    Table1Array.append((row[0],row[1],row[2])
print(str(len(Table1Array))+" records in Table1 loaded successfully.")

You can follow this link to get more information about working with MS Access by Python :

https://elvand.com/python-and-ms-access/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM