分享

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

 区区收藏 2020-07-23

如何在Python中创建mdb数据库文件?(How do you create a mdb database file in Python?)

967 IT屋

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.)

我想在Windows中使用Python创建一个mdb数据库文件,而且似乎无法通过Python文档找到它。我读到的所有内容都与连接和使用光标有关。



任何想法?感谢...


解决方案

我在使用 comtypes 模块已经相当不错了。然而,由于 comtypes 模块动态生成COM库包装,因此您可能希望对所使用的方法有一个Access DAO / ADO / VBA引用,因此没有内置文档。



这里是一个简单的例子,它如何工作。 (自己测试一下。)



 来自comtypes.client import CreateObject 

access = CreateObject('Access.Application')

来自comtypes.gen import Access

DBEngine = access.DBEngine
db = DBEngine.CreateDatabase('test.mdb' ,Access.DB_LANG_GENERAL)
#对我来说,test.mdb是在我运行脚本时在我的文档文件夹中创建的

db.BeginTrans()

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

db.CommitTrans )
db.Close()


(移动<$ c后的第二个import语句$ c> CreateObject 行用于类型库的Python包装器模块以前不存在的情况。)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多