ActiveX Data Object (ADO) is Microsofts strategic data access programming model for Windows applications. Based on the Component Object Model (COM) standard, it defines a set of high-level objects whose properties, events, and methods enable somewhat generic access to many data sources. These sources may include traditional database systems, such as the AS/400, and nontraditional applications, such as Microsoft Outlook. In this article, I will examine the important elements of the ADO object model from a programmers viewpoint and show you how to combine ADO, a COM/ActiveX programming language, and AS/400-based data to create an automated document with Microsoft Word. This article contains Visual Basic (VB) examples and assumes the reader has some familiarity with Windows component programming as well as the AS/400.
ADO and Universal Data Access
ADO replaces the data access objects (DAO) and the remote data objects (RDO) models as the new high-level language interface of choice for database applications on the Windows platform. While Windows still supports DAO and RDO, Microsoft has warned of their imminent demise. The reason for this is that ADO is built on top of another Microsoft data access technology, OLE DB. OLE DB and ADO are key ingredients of the so-called Universal Data Access paradigm promoted by Microsoft.
The goal of Universal Data Access is nothing less than the unification of all interfaces used to access data sources found in todays workplace. It was designed to bring all Windows data-oriented interfaces into a single, component-based standard. Thus, OLE DB and ADO are COM-based: Their interfaces are described by a set of COM objects. Because they are COM-based, they may interoperate with other COM components, tools, and platform services. They also operate in component-supporting applications, such as the Microsoft Office suite. OLE DB is the low-level interface standard, implemented primarily by database vendors. ADO is the high-level interface implemented by Microsoft. In a nutshell, ADO masks the more-complex OLE DB interfaces to provide an easy-to-use object model. Additionally, the COM objects of ADO are ActiveX objects, qualifying them for use in script language environments, such as those used in Active Server Pages (ASPs).
AS/400 Access with Client Access
As of V3R1, IBMs Client Access for Windows includes an OLE DB provider implementation, which may be used with ADO to access the AS/400. It also has an ODBC driver implementation, which may be used with Microsofts ODBC/OLE DB adapter provider and ADO to access the AS/400 or any other ODBC-enabled database. Microsoft has provided the ODBC adapter as an interim measure to help database vendors and programmers get started with ADO. Your ADO programs will likely run more efficiently if they use the native OLE DB provider distributed by the database vendor. See the sidebar
Learn Much ADO on page 46 for more information on using the Client Access OLE DB provider or ODBC.
The object model of ADO was designed for simplicity and flexibility. It consists of six major objects, each reflecting an important detail of database access: Connection, Command, Parameter, Recordset, Field, and Error. Access is initiated via the Connection object, which represents a client/server connection to a database source. The Command object represents an access request, such as a query. The Recordset object defines the set of data associated with the use of a command or with the connection itself. The Parameter object represents any parameters that might need to be passed to a query or stored procedure via a Command object. The Field object represents the column data of the recordset. Finally, the Error object may represent an error returned from the data source. One view of the relationships between these objects is illustrated in Figure 1.
The Connection object is the pivot point for all other ADO objects. It has the expected methods, Open and Close, for initiating and terminating a connection to the data source. Its Execute method is used to initiate a request to the data source. This request can vary greatly depending upon the provider being used, but it is often an SQL statement or stored procedure call. The following Visual Basic code opens a database and performs a simple SQL query:
Dim adoCnxn As New ADODB.Connection
adoCnxn.Open Provider=IBMDA400;Data" & _
adoCnxn.Execute Select * from contacts" & _
"order by company, , adCmdText
The Open method accepts a string describing the connection. The Provider=x substring must be present in this string so that ADO can identify the underlying OLE DB provider; in this case, it is the Client Access OLE DB provider IBMDA400. The remainder of this string is interpreted by the provider. MY400 identifies a valid Client Access connection to a particular AS/400.
The Execute method performs an SQL query. Notice that you can omit the second, optional parameter, which would return a record count. The adCmdText parameter identifies the command string as representing a textual command as opposed to a stored procedure or some other provider-dependent designation. The Connection object also has transaction-processing methods and several performance-tuning properties.
You may use the Command object as an alternative to the Connection objects Execute command. In many cases, it is efficient to describe an access request with a reusable object. It can also be convenient to use more than one Command object for such things as
accessing multiple database files. You could create a Command object to replace the Execute method in the previous examples (omitting the code to open the connection) in the following manner:
Dim adoCmd as New ADODB.Command
adoCmd.CommandText = Select * from" & _
"contacts order by company
adoCmd.CommandType = adCmdText
Set adoCmd.ActiveConnection = adoCnxn
This technique appears to require more effort, but, when you begin to use complex queries, the Command object can be very useful. The Command object contains the Prepared property, which may be used by providers that allow a compiled version of the command to be cached on the server, such as a compiled SQL command. The Client Access OLE DB provider supports this and allows SQL commands to be compiled and optimized once, then run multiple times, saving processing time on the server.
So far, it appears that ADO has been designed for SQL-based access. But you should note that ADO is suitable for use with other access patterns. The provider determines how Command strings are interpreted and, therefore, how they may be used for other access mechanisms. For example, the Client Access OLE DB provider allows record- level access as well as SQL-based access (see the related Redbook mentioned in the sidebar).
The most commonly used feature of the Command object is its support of operations with variable data. Suppose you now want to change the SQL query to retrieve rows containing a column with a certain value, such as Select * from contacts where company=? For this type of operation, a Parameter object is required.
ADO uses the Parameter object to bind runtime values to Command object operations. At runtime, you want to replace the question mark (?) with the value of a variable named companyName. This can be accomplished in VB with the following code:
Dim adoParm as New ADODB.Parameter
Dim companyName as String
adoCmd.CommandText = Select * from" & _
"contacts where company=?
adoCmd.CommandType = adCmdText
Set adoCmd.ActiveConnection = adoCnxn
Set adoParm = _
adoParm.Value = companyName
Here, Ive used the CreateParameter method of Command to create a parameter for the query. The Parameter object is named P1; its a character-type value (adChar). Its specified for input to the Command (adParamInput), and it has a length of 30 characters. In the line that follows, the Parameter objects Value property is set to the value of the variable. Next, the Parameter object is added to the Command objects Parameters collection. A collection is a special property of an object containing references to a set of
similarly structured properties; in this case, it is a set of parameters passed to a command. Finally, the Execute method is called to run the query.
By now, you may be wondering, What about the data? Your program will use the Recordset object to retrieve the results of Command object executions, which, for query operations, may contain data. In fact, the Execute methods youve seen in the examples thus far return a Recordset instance as a result; you simply have not yet assigned that result to an instance variable. This task is a simple object variable assignment involving Set, as follows:
Dim adoRcdset as New ADODB.Recordset
Set adoRcdSet = adoCmd.Execute
The Recordset object is often compared to the AS/400 concept of subfiles. It reflects a set of records returned by the provider. Methods are provided to iterate and move a cursor through the records. Properties reflecting the cursors position (AbsolutePosition, EOF, and BOF) are set as you use these methods. You can use the Bookmark property to remember the current position of the record cursor in order to return to it after some other processing of the Recordset.
In another example of ADO flexibility, the Recordset object is used to retrieve records without the direct use of either Command or Connection objects:
Dim adoRcdset As New ADODB.Recordset
adoRcdset.Open Select * from contacts" & _
order by company, _
Provider=IBMDA400;Data" & _
"Source=MY400;, , , adCmdText
The Open method fills the adoRcdset object with data from the query command. The methods first parameter may be any variable that evaluates to a valid Command object; in this case, it is simply a command string that the Open method internally converts to a Command object. Likewise, the second parameter is a connection string that is used to create a Connection object internally. Note that, instead of passing them, you could have used object variables for Command and Connection objects.
The most important collection contained by a Recordset is the Fields collection. This is where the data is (finally!). The Fields collection consists of a set of Field objects. Data values to be viewed or changed are contained in Field objects. The Field object contains properties reflecting the type of the data, including size, numeric properties, and column name.
The default property of a Field is its Value property; this makes it easy to access the data, as shown in the following example of accessing the COMPANY field of a record:
Dim companyVar as String
companyVar = adoRcdset.Fields(COMPANY)
companyVar = adoRcdset.Fields(1)
companyVar = adoRcdset.Fields(1).Value
To illustrate a couple of points, the last three lines actually do the same thing, assigning the value of the COMPANY field to the companyVar string. The second line grabs the fields default property, which happens to be the fields value, by referencing it
by name (COMPANY). You can reference any Field object in a recordset by name. You can also reference it by position within the recordset, as is shown in the third line. Since the field COMPANY is the first one in the recordset, the company name is returned. The fourth line specifies exactly which property to retrieve from the first field in the recordset. In this case, youre again retrieving the fields actual data by referencing its Value property. This is done implicitly in the second and third lines, because Value is the default property of the Field object. Other properties you can reference include things like the type and size of the field.
ADO error-handling allows data source providers to append Error objects to the Errors collection of the active Connection object of an ADO operation. This is important when operations consist of several steps or when error details cannot be provided by a single error code. Although ADO also uses the standard ActiveX error-handling mechanism (in VB, this is exposed through the Error object), the Errors collection allows for a finer grain of error detail. The Client Access OLE DB provider supports this, and members of the Errors collection reflect information similar to what appears in an AS/400 job log when an error occurs.
An ADO Example Application
The example ADO application is a simple fax cover-sheet generator. Implemented as a Word add in, this program uses the ActiveX components of Word and ADO for manipulating the front-end Word document and calling the OLE DB provider. On the back- end, Client Access and the AS/400 provide the data. The document template used is a slightly modified version of the contemporary fax template distributed with Word. Upon invoking the add-in function, a dialog prompts for the name of the company to send the fax to. Using this name, a query for the companys contact information is formed, and the results are used to populate the recipient and fax number fields of the fax template. Figure 2 shows a cover sheet that was created with the add-in and includes contact information for the Microsoft company.
The add-in was built with Microsoft Visual Basic for Applications (VBA), yet another subset incarnation of VB. Microsoft specifies VBA as the script language for the Office 2000 product line. Creating Word add-ins is extremely easy with VBA. You simply create a new template in Word, press Alt + F11, and you get an IDE very similar to the standard VB IDE. From there, you use the components of Word to write your add-in. Then save your application as a .dot Word document template file to be subsequently loaded and run in Word. (This example is availableas a zip archivefor download from the MC Web site at www.midrangecomputing.com/mc.)
Look at the data access code in the example. First, ADO Connection, Command, and Parameter objects are defined as properties of the data access class module. The Class_Initialize subroutine is called when an instance of the class is created. In Class_Initialize, you first set the properties of the command to be used to query for the contact information as follows:
adoCmd.CommandText = SELECT * FROM" & _
"CONTACTS WHERE (COMPANY=?)
adoCmd.CommandType = adCmdText
CONTACTS is the name of the file to be accessed on the AS/400. CONTACTS is a simple physical file keyed on the COMPANY field. It contains three other
fieldsCONTACT, FAX, and VOICEcontaining a contact name, fax number, and voice number, respectively. Notice that the query specifies a variable parameter. The next two lines of Class_Initialize set up the parameter as follows:
Set adoParm = _ adoCmd.CreateParameter(companyval, _
adChar, adParamInput, 30, )
This appends a new parameter to the empty Parameters collection of the command. Now you are ready to handle query requests, as exposed by the classs GetContact subroutine. The following subroutine accepts the company name as an input parameter and returns a fax number and contact name. It opens the connection, sets the parameter value, executes the query, obtains any results, and, finally, closes the connection.
Dim adoRcdSet As ADODB.Recordset
adoCnxn.Open Provider=MSDASQL.1; & _
adoParm.Value = company
Set adoRcdSet = adoCmd.Execute
If adoRcdSet.EOF = False Then
faxnumber = _
contact = Trim(adoRcdSet.Fields _
After the Execute call, check for results by examining the EOF property of the Recordset object. If it is not empty, the fields of the first (and hopefully only) record are read and assigned to the return variables faxnumber and contact. You might notice that the MSDASQL provider is specified in the Open method. This is the Microsoft ODBC adapter provider, which, in this case, references an ODBC data source name (DSN). This DSN is set up to use the Client Access ODBC provider.
Ill leave to you the complete analysis of the module, manipulating the Word components to create the document. Basically, this consists of two standard add-in subroutines, AutoExec and AutoExit, called by Word when the add-in is loaded. This boilerplate is adapted from a Microsoft how to document for add-ins (see the sidebar for more on this). AutoExec uses Word interfaces for adding an item to the Tools menu. This allows the add-in to be invoked by the user (from the Tools menu, select Send a customer fax). It also registers the name of the subroutine to invoke when the menu item is selected. This subroutine creates an instance of the class module, opens the fax template document, prompts the user for input, and calls the GetContact routine.
Is ADO Right for You?
Most major database vendors already support OLE DB, and more will follow. Also, many directory-oriented services are OLE DB/ ADO-enabled, such as Active Directory. Unless you are coding in C++ or another language suitable for using the OLE DB interfaces directly, ADO is a simple alternative. Also consider other aspects of ADO and Universal Data Access not mentioned here when assessing this technology, such as the Remote Data Service (RDS) facility of ADO. Finally, despite what Ive covered here, remember that ADO is not SQL-centric, though it is SQL-enabling. Although the interfaces of ADO are open-ended by nature, most providers, including the Client Access OLE DB provider, seem to be fairly compliant in their implementations.
Learn Much ADO
As with most Microsoft technologies, there is a plethora of information about ADO and Universal Data Access on the companys Web site. The entry point for this is the UDA home page at www.microsoft.com/data. Next, youll want to see the IBM AS/400 SDK for ActiveX and OLE DB page at as400.rochester.ibm.com/clientaccess/oledb/SDKDescr.htm. From there, you can get to the excellent Redbook A Fast Path to AS/400 Client/Server Using AS/400 OLE DB Support, which details the Client Access implementation and ADO/OLE DB in general and its record-level access capabilities in particular; the Redbook is at publib.boulder. ibm.com/pubs/pdfs/redbooks/sg245183.pdf. For more information about Visual Basic for Applications and automating Microsoft Word, you will want to see Microsoft Office Developer Web Forum at www.microsoft. com/worddev/w-a&sa.htm. For hints about the amazing things you can do with the ActiveX objects provided by Word, see the Microsoft Word Objects page at www.microsoft.com/OfficeDev/Articles/OPG/
007/007.htm. Finally, to see the example application and its source code, download the zip archive from the MC Web site at www.midrangecomputing.com/mc. This zip archive contains several files that make up the application. Although the app is saved as a Word template, the modules of the app have been exported to standard VB text format, so you can see the code even if you dont have VB, VBA, or Word. For more details, see the README.TXT file in the zip archive.
Field Field Field Field
Parameters Command Parameter
Parameter Parameter Parameter
Figure 1: The Execute methods of Connection and Command may produce Recordset objects, which consist of a set of data fields.
Figure 2: The example fax cover-sheet generator uses the ActiveX components of Word and ADO for manipulating the front-end Word document and calling the OLE DB provider.