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
LATEST COMMENTS
MC Press Online