Getting to Know JDBC

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


JDBC lets Java programs access relational databases through a standard SQL interface. Just like Java, JDBC is supported by most platforms, including the AS/400. This article shows you how to use JDBC to access DB2/400 data and metadata from a PC. JDBC is simple to use and provides an easy way to access AS/400 data from PC programs.



Java excites and scares me at the same time. The excitement comes from developing programs that run on any machine. The scary part is looking through all the $50, 800-page Java tomes at my local bookstore.



I am finding out, however, that Java is not as difficult as it looks. The topic of this article, Java Database Connectivity (JDBC), is a good example. I sat down to understand JDBC and found out it was very easy to use, especially since I had some good examples to follow.



I hope this article will encourage you to dig into JDBC. If I can do it, so can you.



To understand the purpose of JDBC, you must first understand the purpose of SQL. IBM developed SQL ages ago as part of the System/R project, the experiment to design a relational database management system (RDBMS). The original name was SEQUEL, which stood for Structured English Query Language. The name was later shortened to SQL, which is pronounced either “sequel” or “S-Q-L.”



SQL was designed to define, manipulate, and retrieve data. Many of us use it primarily or exclusively as an ad hoc query tool, but it was intended to be a standard way for high-level language (HLL) programs to interact with a relational database.



JDBC is one way Java programs use SQL to communicate with a database. I’m told other methods are in the works.






Components of JDBC



JDBC has four components—driver manager, connection, statement, and result set. I wrote a short example program, (shown in Figure 1), to illustrate how to use them. Please refer to Figure 1 as I explain the use of these four JDBC components to retrieve and present records from a sample AS/400 database file.



A Java program that uses JDBC must load the driver manager object, DriverManager, before it can communicate with a database. At Label A of Figure 1, I load the AS/400 JDBC driver, found in the AS/400 Toolbox for Java. If I were connecting to some other DBMS, I’d load some other driver instead. If I were going to connect to more databases in the same program, I would load those drivers as well.



If you look at programs written for JDBC on other platforms, you might see the Class.forName method used instead of the DriverManager.registerDriver method. (I will be using the term method throughout this article. A method is simply the object-oriented term for a function that is an explicit part of an object.)



Once the driver manager is loaded, I can establish a connection, as in Label B. The driver manager uses the getConnection method to establish a connection to a database. The various versions of the getConnection method of the DriverManager object accept different parameter lists, but the first parameter is always a Uniform Resource Locator (URL), a unique identifier for the database.



The URL consists of three parts—protocol, subprotocol, and datasource name. For JDBC, the protocol is always jdbc. The subprotocol for DB2/400 is as400. (Contrast this to the World Wide Web, where the protocol is http and there is no subprotocol.)



The datasource I use in the example is the IP address, but, of course, that is not the real address I used when I ran this program. You’ll have to fill in the appropriate value in your JDBC programs.



I chose to add two more string parameters—a user ID and password—after the URL. I represent them here with the values MYUSERID and MYPWD. If I had omitted these parameters, I would have been prompted for them every time this program ran.



Now that the driver manager has established a connection, I’m ready to start sending SQL statements to the database. The connection object creates one or more SQL statements.



I could have chosen from three statement classes: Statement, PreparedStatement, and CallableStatement. The Statement object is good for ad hoc querying. The PreparedStatement class is better in situations in which an SQL statement is executed over and over. Prepared statements are precompiled, so the entire SQL statement does not have to be translated into a usable form each time it is executed. CallableStatement objects are used to execute stored procedures on the server.



In this program, the statement is executed only one time, so I chose to use a Statement object. You can see it at Label C.



Once the statement object is created, I can run SQL commands. This I do at Label
D. I build a simple SQL SELECT command in variable SQLStmt, then run the connection’s executeQuery method to query the database. The DBMS returns a result set, a group of zero or more rows (records) that satisfy the query.



Now my Java program has to read these rows, one at a time (see Label E). It uses the result set’s next( ) method, which is something like FETCH in AS/400 HLL programs that use embedded SQL. The next( ) method moves from row to row the same way an RPG or COBOL READ works its way through a sequential file. The next( ) method returns a Boolean true each time it finds another row in the result set, and it returns false when all records in the set have been processed.



Unlike an HLL READ, next( ) does not copy data into variables. Other ResultSet methods, starting with the letters get, do that. In this example, I’ve used getString( ), a method that returns a data value as a Java string. Some of the other get methods of note are getDate, getInt, getDouble, and getBigDecimal. The getBigDecimal method is especially important because it is used to retrieve the value of DB2/400 zoned and packed decimal fields. For my purpose, the getString method works fine because I am not doing any numerical calculations on the retrieved AS/400 data.



The getString method needs one parameter—the number of the column to return—so getString(1) references the data in the first column of the current row. Since the SQL SELECT statement asked the DBMS for columns (fields) CUSNO and CUSNM, getString(1) refers to CUSNO (customer number), and getString(2) refers to CUSNM (customer name).



Inside the while loop (at Label E), the println method displays the customer number, tabs to the next tab stop, displays the customer name, and moves to the next line. All that’s left to do is close everything down and end the program.



Running the Program



I compiled and ran this program in a DOS window on a Pentium running Windows 95. The compiler I used was the JDK, Version 1.1.3. The AS/400 was MC’s RISC machine, to which I connected through the Internet.



Here’s what I had to do to make this run: First, I had to compile the program. To do so, I created a directory called jt400 on the Pentium’s hard disk and installed the file jt400.jar, from the AS/400 Toolkit for Java, into it. To make the program find this jar file, I set the CLASSPATH environment variable to point to the jar file:



C:> SET CLASSPATH=.;C:jt400jt400.jar



To compile, I ran this command from a command line:



C:> javac



To run the program, I dialed up my ISP and connected to the Internet. Then, I typed this command:



C:> java JDBCExample01



Figure 2 shows what I saw on the monitor of my PC. As I requested, DB2/400 sent the customer records to my Java program in name sequence, and the Java program dumped them to the screen.



If the only thing JDBC could do is retrieve data from servers, it would be useful. But JDBC has another powerful capability. JDBC can retrieve data about data, or metadata, as it’s called. The Connection and ResultSet classes both have getMetaData methods.



Program (Figure 3) illustrates how these methods work. To help you understand the metadata methods, I’ve included the output of the program in Figure 4.



At Label A of Figure 3, Connection’s getMetaData builds an object of type DatabaseMetaData. This object contains information about general things, like the URL to which the program is connected, the driver, and the DBMS.






The rsmeta object, at Label B, uses the getMetaData method to retrieve information about the columns (fields). It can determine how many columns are in the result set and the characteristics of each one. I’ve made this program tell the name, data type, and size of each column. If you want to see all of the methods available to you, run the following javap command.



C:> javap java.sql.ResultSetMetaData



The ability to access metadata opens the door for all sorts of possibilities for query tools and flexible applications.



Some Final Points



I hope you’re convinced that JDBC is not hard to use, even if you don’t fully understand all the things I’ve shown you. Keep working with it, and I’m sure it will eventually make sense.



Now, let me add a few points: First, these programs are portable to other clients. Ideally, I should be able to port these class files to other types of machines, and they should run against the same server.



Second, these programs are portable to other servers. If I had a CUSTMAS table of the identical description defined in an Oracle database on a UNIX machine,



I would have to change only the registerDriver statement. Third, you don’t have to use two machines to run JDBC. You can compile and run a Java program on an AS/400 and access that same AS/400’s database through JDBC.



Fourth, JDBC is slow (relatively speaking). It may not always provide an acceptable response time. You may find you need to use other methods, such as record- level access, in some situations. (See “Record-level Access with the AS/400 Toolbox for Java” in this issue of MC for more about record-level access.)






Accessing AS/400 Data Using the AS/400 Toolbox for Java java/java.htm Horton, Ivor. Beginning Java. Birmingham, UK: Wrox Press, 1997. Savit, Jeff, Sean Wilcox, and Bhuvana Jayaraman. Enterprise Java. New York;



McGraw-Hill, 1998.


import java.sql.*;

public class JDBCExample01 {

public static void main (String[] args) {

Connection con = null;

try {


// Load the JDBC driver




// Connect to the database

String sourceURL = “jdbc:as400://”;

con = DriverManager.getConnection (sourceURL,”MYUSERID”,”MYPWD”);

// Use this version of getConnection if you want the user

// to be prompted for user ID and password

// con DriverManager.getConnection (sourceURL);


// Run an SQL SELECT statement

Statement stmt con.createStatement ();



ResultSet rs stmt.executeQuery (SQLStmt);


// Display each row (record) retrieved by the SQL statement

while ( ()) {

System.out.println ( rs.getString (1) + “ ” +

rs.getString (2) );



rs.close ();

stmt.close ();


catch (Exception e) {

System.out.println (“ nERROR: “ + e.getMessage());


finally {

try {
con.close ();


catch (SQLException e) {



System.exit (0);




Figure 1: The Java client program,



1ACME Fine Foods, Inc. 2Jack Spratt & Sons, Inc. 9Joe’s Waffle Palace 11Pete’s Burger Heaven 3Polyphonic Records, Inc. 12 Tom’s Ice Cream Bazaar



Figure 2: Output of the Java program in Figure 1


import java.sql.*;

public class JDBCExample02 {

public static void main (String[] args) {

Connection con = null;

try {

// Load the JDBC driver


// Connect to the database

String sourceURL = “jdbc:as400://”;

con = DriverManager.getConnection (sourceURL,”MYUSERID”,”MYPWD”);


// Retrieve and display the connection metadata

DatabaseMetaData dbmeta = con.getMetaData();


“ URL: “ + dbmeta.getURL() +

“ Driver: “ + dbmeta.getDriverName() +

“ DBMS name: “ + dbmeta.getDatabaseProductName() +

“ DBMS version: “ + dbmeta.getDriverVersion() +

“ Driver name: “ + dbmeta.getDriverName() +

“ Driver version: “ + dbmeta.getDriverVersion() +

“ User: “ + dbmeta.getUserName() +

“ Read only: “ + dbmeta.isReadOnly());

// Run an SQL SELECT statement

Statement stmt = con.createStatement ();


ResultSet rs = stmt.executeQuery (SQLStmt);


// Retrieve and display metadata about the result set

ResultSetMetaData rsmeta = rs.getMetaData ();

int ColumnCount = rsmeta.getColumnCount ();


“ Number of columns: “ + ColumnCount);

for (int i = 1; i <= ColumnCount; i++) {


“ Column “ + i + “:” +

“ Name: “ + rsmeta.getColumnName (i) +

“ Label: “ + rsmeta.getColumnLabel (i) +

“ Data type: “ + rsmeta.getColumnTypeName(i) +

“ Display size: “ + rsmeta.getColumnDisplaySize(i) +

“ ”);




catch (Exception e) {

System.out.println (“ nERROR: “ + e.getMessage());


finally {

try {

con.close ();


catch (SQLException e) {



System.exit (0);




Figure 3: This Java program retrieves metadata describing the database and the columns


URL: jdbc:as400://

Driver: DB2 for OS/400 JDBC Driver

DBMS name: DB2/400 SQL

DBMS version: 1.0

Driver name: DB2 for OS/400 JDBC Driver
Driver version: 1.0


Read only: false

Number of columns: 9

Column Name Type Size


Figure 4: Output of the program in Figure 3


Ted Holt

Ted Holt is IT manager of Manufacturing Systems Development for Day-Brite Capri Omega, a manufacturer of lighting fixtures in Tupelo, Mississippi. He has worked in the information processing industry since 1981 and is the author or co-author of seven books. 

MC Press books written by Ted Holt available now on the MC Press Bookstore.

Complete CL: Fifth Edition Complete CL: Fifth Edition
Become a CL guru and fully leverage the abilities of your system.
List Price $79.95

Now On Sale

Complete CL: Sixth Edition Complete CL: Sixth Edition
Now fully updated! Get the master guide to Control Language programming.
List Price $79.95

Now On Sale

IBM i5/iSeries Primer IBM i5/iSeries Primer
Check out the ultimate resource and “must-have” guide for every professional working with the i5/iSeries.
List Price $99.95

Now On Sale

Qshell for iSeries Qshell for iSeries
Check out this Unix-style shell and utilities command interface for OS/400.
List Price $79.95

Now On Sale



Support MC Press Online





  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things

    Read Node.js for Enterprise IBM i Modernization Now!


  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!


  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.


  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline



  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.


  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact


  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using as a pre-built development environment



  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.



  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.



  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails


  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.



  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave 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.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY 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.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.