18
Thu, Apr
5 New Articles

Getting to Know JDBC

APIs
Typography
  • 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.

 

 

Why JDBC?

 

 

Components of JDBC

 

 

JDBC has four components—driver manager, connection, statement, and result set. I wrote a short example program,JDBCExample01.java (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 123.123.123.123, 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 JDBCExample01.java

 

 

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 JDBCExample02.java (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.

 

 

Metadata

 

 

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

 

 

References

 

 

Accessing AS/400 Data Using the AS/400 Toolbox for Java

 

 

http://service2.software.ibm.com/as400/ 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 {

BEGIN LABEL A

// Load the JDBC driver

DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());

END LABEL A

BEGIN LABEL B

// Connect to the database

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

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);
END LABEL B

BEGIN LABEL C

// Run an SQL SELECT statement

Statement stmt con.createStatement ();
END LABEL C

BEGIN LABEL D

String SQLStmt = “SELECT CUSNO,CUSNM FROM XXX.CUSTMAS ORDER BY CUSNM”;

ResultSet rs stmt.executeQuery (SQLStmt);
END LABEL D

BEGIN LABEL E

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

while (rs.next ()) {

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

rs.getString (2) );

}

END LABEL E

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, JDBCExample01.java

 

 

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

DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());

// Connect to the database

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

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

BEGIN LABEL A

// Retrieve and display the connection metadata

DatabaseMetaData dbmeta = con.getMetaData();

System.out.println(

“ 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());
END LABEL A

// Run an SQL SELECT statement

Statement stmt = con.createStatement ();

String SQLStmt = “SELECT * FROM XXX.CUSTMAS”;

ResultSet rs = stmt.executeQuery (SQLStmt);

BEGIN LABEL B

// Retrieve and display metadata about the result set

ResultSetMetaData rsmeta = rs.getMetaData ();

int ColumnCount = rsmeta.getColumnCount ();

System.out.println(

“ Number of columns: “ + ColumnCount);

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

System.out.println(

“ Column “ + i + “:” +

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

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

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

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

“ ”);
END LABEL B

}

con.close();

}

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://123.123.123.123

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

User: MYUSERID

Read only: false

Number of columns: 9

Column Name Type Size
1CUSNO DECIMAL7
2CUSNM CHAR 25
3CUSAD1 CHAR 25
4CUSAD2 CHAR 25
5CU SCIT CHAR 14
6CUSSTA CHAR 2
7CUSZIP CHAR 10
8CUSTYP CHAR 1
9CUSCLS CHAR 1

 

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

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: