简体   繁体   English

如何在 Python 中创建 mdb 数据库文件?

[英]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.我想用 Python 在 windows 中创建一个 mdb 数据库文件,但似乎无法用 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.我对comtypes模块的体验相当不错。 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.对于所使用的方法,您可能希望有一个方便的 Access DAO/ADO/VBA 参考,但是,由于comtypes模块动态生成 COM 库包装器,因此没有内置文档。

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.) (对于类型库的 Python 包装器模块以前不存在的情况,在CreateObject行之后移动了第二个 import 语句。)

First download and install Microsoft Access Database Engine 2010 Redistributable if you haven't.如果还没有,请先下载并安装Microsoft Access Database Engine 2010 Redistributable

Then you should install pyodbc module.然后你应该安装 pyodbc 模块。

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 :您可以点击此链接以获取有关通过 Python 使用 MS Access 的更多信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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