29
Fri, Nov
0 New Articles

Introducing Microsoft ADO Programming for the AS/400

General
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

ActiveX Data Object (ADO) is Microsoft’s 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 programmer’s 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 today’s 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, IBM’s 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 Microsoft’s 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.

ADO Objects

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.

Connection

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" & _

"Source=MY400;”
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 object’s 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


Command

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
adoCmd.Execute

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.

Parameter

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 = _
adoCmd.CreateParameter(“P1”,adChar, _
adParamInput,30)
...

adoParm.Value = companyName
adoCmd.Parameters.Append adoParm
adoCmd.Execute

Here, I’ve used the CreateParameter method of Command to create a parameter for the query. The Parameter object is named P1; it’s a character-type value (adChar). It’s specified for input to the Command (adParamInput), and it has a length of 30 characters. In the line that follows, the Parameter object’s Value property is set to the value of the variable. Next, the Parameter object is added to the Command object’s 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.

Recordset

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 you’ve 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 cursor’s 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 method’s 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 field’s default property, which happens to be the field’s value, by referencing it


Field

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, you’re again retrieving the field’s 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 company’s 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 available—as a zip archive—for 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
fields—CONTACT, FAX, and VOICE—containing 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:


Error

Set adoParm = _ adoCmd.CreateParameter(“companyval”, _

adChar, adParamInput, 30, “”)
adoCmd.Parameters.Append adoParm

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 class’s 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;” & _

“Extended Properties=””DSN=ASH”””
adoParm.Value = company
Set adoRcdSet = adoCmd.Execute
If adoRcdSet.EOF = False Then

faxnumber = _

Trim(adoRcdSet.Fields(“FAX”)) _

contact = Trim(adoRcdSet.Fields _

(“CONTACT”))
End If
adoCnxn.Close

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.

I’ll 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 I’ve 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 company’s Web site. The entry point for this is the UDA home page at www.microsoft.com/data. Next, you’ll 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 don’t have VB, VBA, or Word. For more details, see the README.TXT file in the zip archive.

Errors


Error

Fields

Field Field Field Field

Connection Recordset

ActiveConnection


Error Error

Error

Parameters Command Parameter
 Parameter Parameter Parameter

Execute

Execute

Figure 1: The Execute methods of Connection and Command may produce Recordset objects, which consist of a set of data fields.


Introducing_Microsoft_ADO_Programming_for_the_AS-_40008-00.png 406x284

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.


BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: