简体   繁体   English

使用 Python 创建新的 Access 数据库和表

[英]Create new Access database and tables using Python

I'm trying to create an Access database in Python and add two new tables to it.我正在尝试用 Python 创建一个 Access 数据库并向其中添加两个新表。 I'm using win32com and have managed to create the database but can't create the tables.我正在使用 win32com 并设法创建了数据库,但无法创建表。 All I get is unhelpful Windows errors.我得到的只是无用的 Windows 错误。 Can anyone help me?任何人都可以帮助我吗?

The following code works fine:以下代码工作正常:

dbname = r'C:/Users/Guest/Desktop/NewDB.mdb'
db = Dispatch("Access.Application")
dbEngine = db.DBEngine
workspace = dbEngine.Workspaces(0)

dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0'
newdb = workspace.CreateDatabase(dbname, dbLangGeneral, 64)

How do I add new tables to this database?如何向该数据库添加新表?

Because MS Access is both a GUI .exe application and a backend database, to create a database is a different process than creating database objects like Tables , Views (ie, stored queries), and even Procedures .由于 MS Access 既是 GUI .exe 应用程序又是后端数据库,因此创建数据库与创建数据库对象(例如视图(即存储查询)甚至过程)的过程不同

As a comparison, the other file-level RDMS, SQLite, one must open its .exe shell to CREATE DATABASE .作为比较,另一个文件级的 RDMS,SQLite,必须打开它的 .exe shell 才能CREATE DATABASE And the server-level RDMS's (SQL Server, MySQL, Postgres) one must log into the server instance to run the command.而服务器级 RDMS(SQL Server、MySQL、Postgres)必须登录到服务器实例才能运行命令。 MS Access does not have the shell or instance facilities, just an application object. MS Access 没有外壳或实例设施,只有一个应用程序对象。

Therefore, after creating a database with CreateDatabase method, consider running a DDL SQL statement to CREATE TABLE which you can do with the Execute() method.因此,在使用CreateDatabase方法创建数据库后,请考虑运行 DDL SQL 语句来CREATE TABLE ,您可以使用Execute()方法执行此操作

Python COM Interface Python COM 接口

from win32com.client import Dispatch

try:
    dbname = r'C:/Users/Guest/Desktop/NewDB.mdb'
    accApp = Dispatch("Access.Application")
    dbEngine = accApp.DBEngine
    workspace = dbEngine.Workspaces(0)

    dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0'
    newdb = workspace.CreateDatabase(dbname, dbLangGeneral, 64)

    newdb.Execute("""CREATE TABLE Table1 (
                      ID autoincrement,
                      Col1 varchar(50),
                      Col2 double,
                      Col3 datetime);""")

except Exception as e:
    print(e)

finally:
    accApp.DoCmd.CloseDatabase
    accApp.Quit
    newdb = None
    workspace = None
    dbEngine = None
    accApp = None

Python DB API Python数据库 API

While the CREATE DATABASE is not available in MS Access SQL you can run the above Execute with any Python ODBC API with a CREATE TABLE command only after database file is created:虽然CREATE DATABASE在 MS Access SQL 中不可用,但您可以仅在创建数据库文件后使用CREATE TABLE命令使用任何 Python ODBC API 运行上述Execute

import pypyodbc

dbname = r'C:/Users/Guest/Desktop/NewDB.mdb'     
constr = "DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={0};".format(dbname)

dbconn = pypyodbc.connect(constr)

cur = dbconn.cursor()
cur.execute("""CREATE TABLE Table1 (
                 ID autoincrement,
                 Col1 varchar(50),
                 Col2 double,
                 Col3 datetime);""")
dbconn.commit()

For the benefit of future readers, the sample code in the question uses win32com to create the new Access database file.为了将来读者的利益,问题中的示例代码使用win32com创建新的 Access 数据库文件。 A simpler alternative would be to use my (free) msaccessdb Python module, eg,一个更简单的替代方法是使用我的(免费) msaccessdb Python 模块,例如,

import msaccessdb
import pyodbc

db_file = r'C:\path\to\new.accdb'
msaccessdb.create(db_file)
cnxn_str = (
    'DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};'
    'DBQ={}'.format(db_file)
)
cnxn = pyodbc.connect(cnxn_str)

It looks like you would execute a SQL statement CREATE Table on the Database object ie on newdb , via its Execute() method.看起来您将通过其Execute()方法对Database对象(即newdb Execute()执行 SQL 语句CREATE Table

But I don't recommend using COM on MS Access Application object.但我不建议在 MS Access Application对象上使用 COM。 For an MS Access database, the recommended method of interacting with the DB is to directly open the DB through ODBC API, rather than through an Access.Application instance.对于 MS Access 数据库,推荐的与 DB 交互的方法是通过 ODBC API 直接打开 DB,而不是通过Access.Application实例。 You should only use the latter if you need features from the app like reports, printing, etc. For interacting with MS Access DB file via ODBC, I have had good experience with pyodbc and pypyodbc, which do not require COM.如果您需要应用程序的功能,如报告、打印等,您应该只使用后者。对于通过 ODBC 与 MS Access DB 文件进行交互,我在 pyodbc 和 pypyodbc 方面有很好的经验,它们不需要 COM。 A lower level access through DAO API via win32com (but not Access.Application) seems quite good too but I have not tried.通过 win32com(但不是 Access.Application)通过 DAO API 进行较低级别的访问似乎也很好,但我还没有尝试过。 Check out http://www.icodeguru.com/WebServer/Python-Programming-on-Win32/ch13.htm for a good discussion on various connection API available and some code examples.查看http://www.icodeguru.com/WebServer/Python-Programming-on-Win32/ch13.htm以获得关于各种可用连接 API 和一些代码示例的良好讨论。

Other useful resources:其他有用的资源:

  • ms access application automation API : the examples use vba but win32com provides same API. ms 访问应用程序自动化 API :示例使用 vba,但 win32com 提供相同的 API。
  • intro to the above with links for ADO-based tasks that therefore don't need the ms access application: links show c# but win32com provides same API.上面介绍了基于 ADO 的任务的链接,因此不需要 ms access 应用程序:链接显示 c# 但 win32com 提供相同的 API。
newdb = workspace.CreateDatabase(dbname, dbLangGeneral, 64)

已经创建了一个名为newdb的 DAO.Database 对象,所以你应该能够简单地继续使用它的Execute方法来运行这样的 DDL 语句

newdb.Execute("CREATE TABLE [Table1] ([ID] COUNTER PRIMARY KEY, [TextField] TEXT(50))")

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

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