16
Tue, Apr
5 New Articles

The Way We Word: Record-Level Access Revisited!

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

Back in June, I wrote a column describing, among other things, how to use IBM's index access object to speed up record-level access. Then I got a letter--well, an email--from IBM's own Troy Bleeker:

"Chris,

I just saw your article in my email. I own the OLE DB provider that you wrote about for MC Mag Online. Thank you for a good, detailed article. Well written. You have hit the essence of the usefulness of record-level access: quick look-ups."

This is very technical language, so permit me to translate: "Devous, you are brilliant. Your keen mind and sharp wit are overshadowed only by your rational and humble personality. You should be writing operating systems, not articles! You are severely underpaid!"

There, that clears that up. Troy continued:

"However, I'm writing to tell you that you might want to investigate the Seek method of ADO. You said ADO did not have one, but it has. Ever since ADO 2.1 (I'm pretty sure), but certainly 2.5 on up has it.... We added support for this method in V5R1M0. Many customers should be moving toward this release if not already there."

He's right. I did say that, and I was wrong. What I should have said was that the Client Access ADO provider that comes with Client Access Express V4R5 and below doesn't support use of ADO's index property or seek method. The column dealt, in part, with using IBM's AD400 index object to overcome this limitation.

Troy added:

"Why is it important? Who cares? Well, we are recommending that people stop using the AD400 index object. It will not get any enhancements. For example, it will not be 64-bit processor enabled. Also, it requires jobs on the AS/400 to do its work. The index.GetBookmark must operate on a second job to find the bookmark, then that bookmark is used on the recordSet. Move, and the real job gets positioned. It was only meant as a workaround while ADO did not have the support. Since ADO has that now, everyone should be using it.

"Our Visual Basic wizards in V5R1M0 generate VB code without the index object and our V5R1M0 samples, downloadable from the Web here, http://www.ibm.com/servers/eserver/iseries/access/oledb/samples.htm use the new recordSet.Seek() method as well.

"I just thought you might want the latest info to make your next, follow-up article (hint) the best it can be.

"Thanks,

Troy C. Bleeker
IBM eServer iSeries Data Providers"

Thanks for the hint, Troy, and the kind words.

So, how can you move from using the AD400 index object to using the IBMDA400 provider's seek and index support? Well, it ain't as hard as it sounds, so here we go!

Excel-lent Beginnings

In the June column, I detailed how to create a table with an index and then access records in that table using its index. The purpose was to update records in an Excel spreadsheet based on iSeries data. That example was pretty detailed because I wanted to illustrate the power of the ADO provider when combined with indexes and the use of SQL. Since we're only concerned with one topic here, we'll use something a little simpler.

For this month's example, I've created a spreadsheet with a list of UPC codes. The codes represent products, but let's pretend we don't know which products and need to find out. Let's use a VBA macro to process each record in the spreadsheet, and then do a seek to find the UPC code on the iSeries, and then fill in the blank fields.

The Building Blocks

The product I am working with is sportswear--polo shirts and T-shirts. The UPC translates to a specific style, color, and size of shirt, with a specific logo embroidered on the left of the chest. I know the UPC, and I want to know what values the other components are.

Column A Column B Column C Column D Column E Column F
UPC Code Logo Number Description Style Color Size

Figure 1: What goes where?

The table in Figure 1 details what the various columns of the spreadsheet contain. Since I have the UPC code, it'll be the VBA project's job to fill in the remaining columns. So, I'll access the VB editor in Excel (either from the Tools menu or by pressing Alt+F11) and insert a module.

Before I start writing code, I need to add the Microsoft ActiveX Data Objects library to my project references (it's on the Tools menu in the VB editor). This will include the objects I need to get at the iSeries data. Remember that the example here assumes I have the Client Access Express V5R1 or better data provider installed. The provider is included with Client Access and installs by default.

How I Did It

Now for the code:

Dim cniSeries As ADODB.Connection
Dim rsUPCbyUPC As ADODB.Recordset
Dim rsItemMasterbyItem As ADODB.Recordset


Sub GetUPCInfo()
Const lStartRow As Long = 2
Dim lLastRow As Long
Dim lThisRow As Long
Dim UPCKey, ItemKey

Application.ScreenUpdating = False

Set cniSeries = New ADODB.Connection
cniSeries.Open "Provider=IBMDA400;Data Source=192.168.1.2;", "", ""

Set rsUPCbyUPC = New ADODB.Recordset
rsUPCbyUPC.CursorLocation = adUseServer
rsUPCbyUPC.Index = "/QSYS.LIB/BPCSCDUSRF.LIB/UPCWEBL2.FILE(*FIRST, *NONE)"
rsUPCbyUPC.Open "/QSYS.LIB/BPCSCDUSRF.LIB/UPCWEBL2.FILE(*FIRST, *NONE)", cniSeries, adOpenStatic, adLockReadOnly, adCmdTableDirect
rsUPCbyUPC.MoveFirst

Set rsItemMasterbyItem = New ADODB.Recordset
rsItemMasterbyItem.CursorLocation = adUseServer
rsItemMasterbyItem.Index = "/QSYS.LIB/BPCS405CDF.LIB/IIML01.FILE(*FIRST, *NONE)"
rsItemMasterbyItem.Open "/QSYS.LIB/BPCS405CDF.LIB/IIML01.FILE(*FIRST, *NONE)", cniSeries, adOpenStatic, adLockReadOnly, adCmdTableDirect
rsItemMasterbyItem.MoveFirst

lLastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

For lThisRow = lStartRow To lLastRow
    Application.StatusBar = "Processing row " & Format(lThisRow, "#,##0") & " of " & Format(lLastRow, "#,##0")
    If Not IsEmpty(UPCKey) Then
       Erase UPCKey
    End If
    If CStr(Cells(lThisRow, 1).Value) = "" Then
       Exit For
    End If
    UPCKey = Array(Cells(lThisRow, 1).Value)
    rsUPCbyUPC.Seek UPCKey, adSeekFirstEQ
    If Not rsUPCbyUPC.EOF Then
       'logo
       Cells(lThisRow, 2).Value = rsUPCbyUPC("UTAPE")
       'style
       Cells(lThisRow, 4).Value = rsUPCbyUPC("UPRDDSC")
       'color
       Cells(lThisRow, 5).Value = rsUPCbyUPC("UCOLRDS")
       'size
       Cells(lThisRow, 6).Value = rsUPCbyUPC("USIZDES")

       'logo description
       ItemKey = Array(rsUPCbyUPC("UTAPE"))
       rsItemMasterbyItem.Seek ItemKey, adSeekFirstEQ
       If Not rsItemMasterbyItem.EOF Then
          Cells(lThisRow, 3).Value = rsItemMasterbyItem("IDESC")
       Else
          Cells(lThisRow, 3).Value = "NOT FOUND"
       End If
    End If
Next

rsItemMasterbyItem.Close
rsUPCbyUPC.Close
cniSeries.Close

Application.StatusBar = "Ready"
Application.ScreenUpdating = True
MsgBox "Done updating spreadsheet!"

End Sub


The meat and potatoes come in two different parts of the dish. Here's the meat:

Set cniSeries = New ADODB.Connection
cniSeries.Open "Provider=IBMDA400;Data Source=192.168.1.2;", "", ""

Set rsUPCbyUPC = New ADODB.Recordset
rsUPCbyUPC.CursorLocation = adUseServer
rsUPCbyUPC.Index = "/QSYS.LIB/BPCSCDUSRF.LIB/UPCWEBL2.FILE(*FIRST, *NONE)"
rsUPCbyUPC.Open "/QSYS.LIB/BPCSCDUSRF.LIB/UPCWEBL2.FILE(*FIRST, *NONE)", cniSeries, adOpenStatic, adLockReadOnly, adCmdTableDirect
rsUPCbyUPC.MoveFirst


I defined the cnIseries variable and the recordset variables above the start of the subroutine so that they would be global to all the subroutines and functions in the project. If I decide to add to this, anything I add will also have visibility to these globally scoped variables.

Note that the recordset object uses a server-side cursor. The index property (upon which the seek depends) requires a server-side cursor. I also have to set the index and cursor properties before I open the recordset. The open command uses IFS syntax, naming the file by its IFS path. *FIRST and *NONE refer to members and journaling, respectively. This syntax applies to both the index property and the open statement.

In opening the file, I name my connection (cniSeries), cursor type, lock type, and command type. In the example, I've used a static cursor, which will not reflect changes made by other users. Seeing changes is not important to me in this context, so I'll avoid a dynamic cursor and speed up performance. I could also use a forward-only cursor for even better performance. For this application, it would work, but the limitation would be that I could only move forward through the data. (See your ADO documentation for a full explanation of cursor types.)

The lock type tells the provider what type of lock to put on the records. Since I'm not updating, I've used read-only. The command type tells the provider how to interpret the command string. In this case, I've told the provider that this is a table whose columns will all be returned. I could also use an SQL statement, a stored procedure, or a persistent recordset. (See your ADO reference for a complete explanation.)

I then move the pointer to the first record in the recordset. Without this, the seek will not correctly function because you must access the recordset for the seek to return EOF when a match is not found on a seek equal. Note that with a server-side cursor, you have to explicitly release the record or close and reestablish the recordset to move the pointer.

Now, the potatoes:

UPCKey = Array(Cells(lThisRow, 1).Value)
rsUPCbyUPC.Seek UPCKey, adSeekFirstEQ
If Not rsUPCbyUPC.EOF Then

[SNIP]

End If


UPCKey is a variant. To do the seek, make it an array of values. This is very like establishing a keylist in RPG. You can use all of the key fields or the first few. If you use more than one, you have to go in order, following the defined key. For example, if your file is keyed on Field 1, Field 2, and Field 3, you can use Field 1, or Field 1, 2, and 3, or Field 1 and 2, but not Field 1 and 3.

So you set up your key list by using array(Value, Value, Value...). In this case, I'm using only one key, so I use only one value. Then, I execute the seek.

It should be noted that, at this writing, the seek method incorrectly assumes that the order of key fields in the key list will match the order of those fields in the table. That is, if you have a table with Field 1, Field 2, Field 3, it is assumed that you won't create a key like Field 3, Field 1. There is an APAR on this issue (SE08268), and it should be resolved shortly. In the meantime, for multiple key seeks, build your logicals so that the fields are in the same order as the physical.

When executing the seek method, you must provide the key and the seek type. In this case, I'm looking for a record equal to my key, so I use the adSeekFirstEqual value. This will find a match or set the recordset to EOF if there is no match. If you are not at end of file, set the value in your cells and search for the tape description in item master, using the same technique used for the UPCbyUPC recordset.

Figure 2 shows the seek types and what they do:

adSeekFirstEQ
Seeks the first record whose key is equal to the key array
adSeekLastEQ
Seeks the last record whose key is equal to the key array
adSeekAfterEQ
Seeks either a record whose key is equal to the key array or a record just after where that match would have occurred
adSeekAfter
Seeks a record key just after where a match with the key array would have occurred
adSeekBeforeEQ
Seeks either a record with a key equal to the key array or just before a matching record
adSeekBefore
Seeks a record just before a matching record

Figure 2: This table shows the seek type enumerators.

Running the macro fills in the values, as shown in Figure 3:

http://www.mcpressonline.com/articles/images/2002/rlarevisitedV400.png
Figure 3: The spreadsheet...before and after.

Like the AD400 index provider, this method is lightning fast. It also has the advantage of lower overhead at the iSeries than the older method had. If possible, you should begin using this in favor of the AD400 index provider, which is more or less discontinued and will not be supported on the new 64-bit machines.

This technique is particularly useful when you want to open one recordset but look for records matching varying values. When SQL won't do, this can be extremely useful. I encourage you to try this at your own site, because it can help you to produce more powerful applications, and your users to work more productively.

Drat! He got me! OK, I gotta get my focus back on Doom!


Chris Devous is the Director of IT Systems Development at The Antigua Group, Inc., a Peoria, Arizona, garment manufacturer. Chris has been in IT since '82 and lives Arizona with his wife, three children, a bird, two dogs, a cat, and various marine life forms. He can be reached by email at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

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: