Connecting with Data Access Objects
The Data Access Object hierarchy is installed on your system if you have Microsoft Office, Access, or Visual Basic, or if you have ever installed a VB application that works with MDB files. It doesn’t need an ODBC data source configured. We recommend running MakePy over the latest version of the Microsoft DAO Library on your system, as seen in Figure 13.3.
The hierarchy starts with a database engine (class
DBEngine
) and allows you to open multiple
Database
objects. Once a database is open you
can create Recordset
objects that are the broad equivalent
of a cursor in the Python Database API. You can navigate through a
Recordset
and edit its fields. A
Field
is an object too, with a
Name
, a Value
, and many more
properties.
Let’s start by connecting to the same database as before. This time you don’t need the ODBC data source, but can go straight for the file:
>>> import win32com.client >>> daoEngine = win32com.client.Dispatch('DAO.DBEngine') >>> daoDB = daoEngine.OpenDatabase('C:\\MYDIR\\pydbdemos.mdb') >>> daoRS = daoDB.OpenRecordset('SELECT ClientID, InvoiceDate, \ Consultant, Hours FROM Invoices') >>> daoRS.MoveLast() # need to do this to get an accurate size >>> daoRS.RecordCount 4 >>>
Opening the database and getting the result set is no harder than with the Python API and ODBC. However, instead ...
Get Python Programming On Win32 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.