Using JDBC With Iseries
Using JDBC With Iseries
Using JDBC With Iseries
Published by Bits & Bytes Programming, Inc. Valley Center, CA 92082 [email protected]
Table of Contents
The need for JDBC.................................................................................................................. 3 About JDBC Drivers................................................................................................................. 4 Features required for an iSeries JDBC driver ................................................................................ 4 Driver Categories .................................................................................................................... 5 Type 1 JDBCODBC Bridge ................................................................................................ 5 Benefits .......................................................................................................................... 5 Drawbacks ...................................................................................................................... 5 Type 2 Native API .............................................................................................................. 5 Benefits .......................................................................................................................... 5 Drawbacks ...................................................................................................................... 6 Type 3 JDBC Net............................................................................................................. 6 Benefits .......................................................................................................................... 6 Type 4 Native Protocol......................................................................................................... 6 Benefits .......................................................................................................................... 6 iSeries 400 JDBC Drivers.......................................................................................................... 7 Developer Kit for Java driver .................................................................................................... 7 Specifying the class ........................................................................................................... 8 URL for access ................................................................................................................. 8 Toolbox for Java................................................................................................................... 8 Specifying the class ........................................................................................................... 8 URL for access ................................................................................................................. 8 Running the Toolbox driver on the same iSeries 400 ........................................................................ 9 JDBC Objects and their relationships............................................................................................10 JDBC class .......................................................................................................................10 Driver Manager...................................................................................................................10 Connection........................................................................................................................10 Statement..........................................................................................................................10 ResultSet ..........................................................................................................................10 The java.sql package ...............................................................................................................11 Package javax.sql...................................................................................................................12 ConnectionPoolDataSource....................................................................................................12 DataSource ....................................................................................................................12 PooledConnection.............................................................................................................12 RowSet..........................................................................................................................12 Using JDBC Load the driver ....................................................................................................13 Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie 1
Two techniques to load the driver..............................................................................................13 Which driver to load .............................................................................................................13 Using JDBC get a connection ..................................................................................................14 The connection URL .............................................................................................................14 Connection URL for the Native driver.......................................................................................14 Connection URL for the Toolbox driver.....................................................................................14 Specifying the User ID and Password........................................................................................15 Supply the user ID and password...........................................................................................15 Supply the user ID and password in a Properties object................................................................15 Setting JDBC driver properties ................................................................................................15 Properties passed on URL ...................................................................................................15 Properties passed in Properties object.....................................................................................15 Additional Information ...........................................................................................................15 Using JDBC create a statement................................................................................................16 An executeQuery statement ....................................................................................................16 An executeUpdate statement ...................................................................................................16 Using JDBC prepared statements..............................................................................................17 Using JDBC resultset ............................................................................................................19 Using JDBC update the database..............................................................................................20 JDBC and Connection Pool.......................................................................................................21 Configuring a Connection Pool ...................................................................................................22 JDBC / Connection Pool Code ...................................................................................................26 First pass: VA Java, Console output ..........................................................................................26 Second pass: recode as a servlet .............................................................................................29 Third pass: recode to use connection pool...................................................................................32
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
Notably, Microsoft does not provide JDBC drivers for their database products (FoxPro, Access, SQL Server), but there are third-party vendors that provide JDBC support for Microsoft products.
Translation of EBCIDC characters (iSeries 400 native format) to Unicode (Java native format) Conversion of packed and zoned numeric fields to Java numeric data types (BigDecimal, Float, Double, Short, Int, Long) Securely provide a user ID and password from the application to the database for log-on authentication Provide a means to pass additional parameters to the JDBC driver to control its operation (JDBC driver properties)
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
Driver Categories
Type 1 JDBCODBC Bridge
Requires ODBC driver on client
Type 3 JDBCNet
pure Java to middleware to DB
Driver Categories
When you start learning about JDBC drivers, you will find references to the "JDBC driver type" or category of driver. The categories provide a method to assess how a particular JDBC driver can be deployed.
Benefits
Can work with databases that don't have a JDBC driver (example: Microsoft Access, Microsoft SQL Server). Can be used with "desktop" database products to provide a simulated environment of a production database (example: download iSeries 400 tables to Microsoft Access, develop a Java application using those tables, change JDBC driver when program is moved to iSeries 400). Requires the ODBC driver for the database to be installed on the client machine. For example, if you develop a Java application to work with a Microsoft Access database and you then deploy that application and database to client machines, you need to configure the Microsoft Access ODBC driver on each client machine. Additional overhead of going through multiple layers to the target database can impact performance.
Drawbacks
Benefits
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
Drawbacks
Must be installed on the host machine. May be tied to a particular level of the operating system or database.
Benefits
Benefits
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
That statement loads the JDBC driver and registers it with the driver manager. After loading, you can use JDBC calls to get a connection to a specific database, either on the same machine or on another machine.
Where <database_name> is the name of a database directory entry on the iSeries 400 or the special value *LOCAL to point to the local database (the database that is on the same server as the program issuing the JDBC call). The subprotocol modifier jta: (Java Transaction API) provides support for two-phase commit operations. Use this option if you are working with multiple databases in the same application.
This driver establishes a TCP/IP sockets connection from the Java program to the target iSeries 400 database, by way of the iSeries 400 Host Servers. You will typically use this driver in the following situations:
Java applications installed on a client machine Applets that need to connect back to the iSeries 400 database Other servers or server applications that need to work with the iSeries 400 database (for example, run WebSphere Application Server on a Linux or Windows 2000 Server machine and work with the iSeries 400 database).
That statement loads the JDBC driver and registers it with the driver manager. The connection URL is used to specify the iSeries 400 that contains the database you want to work with.
Where <system_name> or <tcpip_address> are used to point to the iSeries 400 machine that contains the database you want to access.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
1) Class.forName(com.ibm.as400.access.AS400JDBCDriver); DriverManager AS400JDBCDriver conn sql 2) Connection conn = DriverManager .getConnection( jdbc:as400://M270/VAJAVA,UID,PWD); 3) Statement sql = conn.createStatement(); 4) ResultSet rs = sql.executeQuery( select * from parts order by partno); 5) while (rs.next()) { rs.getInt(PARTNO); rs.getString(PARTDS); } 6) rs.close(); conn.close(); PARTNO 12301 12302 12303 PARTDS Quad speed CD ROM SCSI II cable 17 inch SVGA Mon rs
JDBC class
The JDBC class is used to create an instance of the JDBC driver. You can use the Class.forName statement to create an instance of the JDBC driver and register it with the driver manager.
Driver Manager
The driver manager is responsible for providing the environment within your application for the JDBC drivers that you might load. Note that you can load as many JDBC drivers as required by your application (use the Class.forName statement for each distinct JDBC driver).
Connection
A connection object is used to create a connection between your Java application and the database. You use the getConnection method of the DriverManager object. The getConnection method uses a JDBC URL to identify the protocol to use (jdbc:), the subprotocol to identify which JDBC driver to use (as400: or db2:), and the TCP/IP host name or address of the machine where the database is located, or the actual name of the database.
Statement
A statement object is created on a specific connection, meaning that the statement is associated with a particular database. The two types of statements are Statement and PreparedStatement. A statement is sent to the database for processing with either the executeQuery or executeUpdate methods of the statement object.
ResultSet
A result set object is created in response to an executeQuery method (SQL SELECT statement). The output of the SELECT statement is returned to your application in the result set. The result set includes only those columns and rows that were selected, based on your query specifications (the result set might be a subset of the rows available in the queried tables). The order of the rows in the result set depends upon the ORDER BY clause, if any, in the SELECT statement. If you run a SELECT statement that selects no rows from the queried tables, an empty result set is returned to your application. A result set is not returned if you use the executeUpdate method. Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie 10
Package java.sql
Contains JDBC classes / interfaces Usually use import statement:
import java.sql.*;
Commonly used:
java.sql.Connection java.sql.DriverManager java.sql.PreparedStatement java.sql.ResultSet java.sql.Statement java.sql.SQLException java.sql.SQLWarning
With the import statement, you can simply refer to the classes as Connection and Statement. Although many Java programmers prefer to use the import statements, they are optional. You may prefer to use complete class names until you become more familiar with the Java package and class structure.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
11
Package javax.sql
Part of J2EE (Java 2 Enterprise Edition) Used in WebSphere programming:
ConnectionPoolDataSource DataSource PooledConnection RowSet
Package javax.sql
The javax.sql package is included in the J2EE (Java 2 Enterprise Edition) version of Java. The J2EE Software Development Kit (SDK) is freely available from Sun Microsystems, Inc. at the following web site:
http://java.sun.com/j2ee/index.html
The J2EE provides support for JDBC extensions, servlets, JavaServer Pages, and other technologies that are commonly used in server-side development (as opposed to client-side and applet development, which is most closely associated with the Java Development Kit). Note that package names in J2EE start with javax not java, for Java extensions. As with the java.sql package, you can use an import statement:
import javax.sql.*;
ConnectionPoolDataSource
A factory for PooledConnection objects. (A factory is an object that is used to create other objects.)
DataSource
A factory for Connection objects. WebSphere Application Server includes configuration objects called data sources, which you can then use in your Java applications.
PooledConnection
A connection object that is able to work in a connection pool (described later in this manual).
RowSet
A row set can be used as a JavaBean in a visual development environment (for example, VisualAge for Java). You can pass parameters to the row set and retrieve results from it, as well as receive events from the row set.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
12
Of the two, Class.forName is preferred, although both statements accomplish the same thing. One advantage of Class.forName is that you can use a variable as the JDBC driver class to load:
Class.forName(jdbcDriver);
By using a variable, you can defer until run-time the actual class name to load. The JDBC class name must be found in the classpath of the JVM that your application is running in.
Java program and database on the same iSeries 400 use the "native" driver (com.ibm.db2.jdbc.app.DB2Driver) Java program running on a different machine, database on the iSeries 400 use the "toolbox" driver (com.ibm.as400.access.AS400JDBCDriver)
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
13
10
the local iSeries 400. If you need to connect to a database on another iSeries 400 or DB2 system that supports Distributed Relational Database Architecture (DRDA), specify that database name instead of *LOCAL. The name that you specify must be entered in the iSeries 400 Relational Database Directory Entries (use the WRKRDBDIRE command to maintain the list).
By varying the host name or TCP/IP address, you can use JDBC to connect to any iSeries 400 that you can access in your network.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
14
/VAJAVA the optional library name that contains tables you want to access. If you omit
Additional Information
You can find more information about JDBC driver connection properties at the iSeries 400 Information Center web site maintained by IBM. Go to the following URL and search for "JDBC Connection Properties"
http://publib.boulder.ibm.com/html/as400/infocenter.html
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
15
PreparedStatement
performance (precompile statement) use variable parameters in statement
11
An executeQuery statement
The most common use for a statement is to run a query. Use the following template (assume that the conn object is initialized as a valid JDBC connection to the iSeries 400):
Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from parts order by partno");
An executeUpdate statement
You can run SQL statements other than SELECT by using the executeUpdate method of a statement object:
Statement stmt = conn.createStatement(); int rowsAffected = stmt.executeUpdate("INSERT INTO APILIB.PARTS (PARTNO, PARTDS) VALUES(19999, 'Test part 19999')")
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
16
12
Although that technique works, it is not ideal from the point of view of the query processor, as it has to parse the statement every time it is sent to the server. The preferred technique is to create a prepared statement and set the variable parameter values at run-time. For example, the previous SQL statement could be handled like this:
String sql = "select * from parts where partno=?"; PreparedStatement pStmt = conn.prepareStatement(sql); pStmt.setInt(1, request.getParameter("PARTNO")); ResutlSet rs = pStmt.executeQuery();
Using this technique, the statement is written with the ? character as a parameter marker. If you have multiple parameters in a statement, you simply put a ? character at each point where a value will be supplied at run-time. After coding the SQL statement, you create a PreparedStatement object using the prepareStatement method of the connection object. To use the prepared statement, use the various setXXX methods of the prepared statement object (for example, setInt, setString). The setter methods all use two parameters: Parameter 1 number of the parameter marker (starting at 1) Parameter 2 value to substitute in place for the parameter marker You must supply a value for each parameter marker in the statement. The value you supply must be valid for the SQL statement (for example, if you are supplying a String value, you need to enclose it in single quote characters). Although it looks like the prepared statement technique is more work, it is one of the primary techniques available to you to improve SQL performance. Although setting the string and creating the prepared statement are shown here immediately followed by the setInt and executeQuery methods, you would most likely put the prepareStatement method in the init() method of your class, meaning that the preparation is done only once when the class is loaded. Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie 17
Another reason why you get improved database performance is because the SQL statement is sent to the server for parsing when the prepareStatement method is called. Because the server can examine the statement before it is used, it can compute the best access plan before the query is processed. Once it has computed the access plan, it saves it so that when the statement is finally submitted for execution (with the executeQuery method), the statement can be processed immediately.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
18
13
The rs.next() method returns true if there is a next row in the result set. The while loop goes through each row in the result set; at the end of the loop, it goes back to rs.next() which retrieves the next row. At the end of the result set, rs.next() returns false and the loop is exited. You can use the getXXX methods on the result set object to get the values of the columns for the current row. The parameter to the getter methods is the column name from the database. Once you retrieve the column of data, you can use it in your Java program as required.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
19
14
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
20
15
16
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
21
17
Figure 1: Select the Create Data Source option in the WebSphere Administrative Console.
JDBC01
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
22
JDBC02
Figure 3: Specify the name for the JDBC driver, its class and URL prefix.
JDBC03
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
23
Figure 4: The Wizard prompts you for the node (server) to install the data source on.
JDBC04
Figure 5: Assign a name to the data source and the name of the database. The data source name is used in your Java program.
JDBC05
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
24
Figure 6: You can configure connection pool parameters on the Advanced tab for the data source.
JDBC07
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
25
23
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
26
Figure 7: This figure show the VisualAge for Java Workbench (background), the Signon to AS/400 prompt, and the Console output window with the output from the JDBC SELECT statement processing.
JDBCVAJ01
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
27
/** * Test JDBC in VisualAge for Java environment * Creation date: (6/13/2001 1:05:33 AM) * @author: Craig Pelkie */ public class JdbcTest1 { /** * JdbcTest1 constructor comment. */ public JdbcTest1() { super(); } /** * Starts the application. * @param args an array of command-line arguments */ public static void main(java.lang.String[] args) { //********************************************* // Initialize the AS/400 JDBC driver class //********************************************* try { System.out.println("Before Class.forName"); Class.forName("com.ibm.as400.access.AS400JDBCDriver"); } catch (ClassNotFoundException cnfe) { System.err.println("ClassNotFoundException for " + cnfe.getMessage()); cnfe.printStackTrace(); System.exit(-1); } //********************************************* // driver initialized, prepare/run SQL //********************************************* try { System.out.println("Before getConnection"); Connection conn = DriverManager.getConnection( "jdbc:as400://M270/VAJAVA;trace=true;errors=full"); System.out.println("Before createStatement"); Statement stmt = conn.createStatement(); System.out.println("Before executeQuery"); ResultSet rs = stmt.executeQuery("SELECT * FROM PARTS ORDER BY PARTNO"); //***************************************** // display column headings //***************************************** System.out.println("Count\tPARTNO\tPARTDS\tPARTQY\tPARTPR\tPARTDT"); //***************************************** // iterate over the result set //***************************************** int i = 0; while (rs.next()) { ++i; System.out.println(i rs.getInt("PARTNO") rs.getString("PARTDS") rs.getInt("PARTQY") rs.getBigDecimal("PARTPR") rs.getDate("PARTDT")); } + + + + + "\t" "\t" "\t" "\t" "\t" + + + + +
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
28
} catch (SQLException sqle) { System.err.println("An SQL exception occurred:"); do { System.err.println("Message: " + sqle.getMessage()); System.err.println("SQLState: " + sqle.getSQLState()); System.err.println("ErrorCode: " + sqle.getErrorCode()); } while (sqle.getNextException() != null); } catch (Exception e) { System.err.println("Exception occurred: " + e.getMessage()); e.printStackTrace(); } System.out.println("** Done **"); System.exit(0); } }
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
29
Figure 8: After recoding as a servlet, the servlet is exported from VAJ to WebSphere. It is then configured in WebSphere, started, and requested in the browser.
JDBCSERVLET01
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
30
/** * Servlet for testing JDBC * Creation date: (10/3/2001 2:47:40 AM) * @author: Craig Pelkie */ public class JdbcPartsServlet extends HttpServlet { /** * JdbcPartsServlet constructor comment. */ public JdbcPartsServlet() { super(); } /** * This method is called by WebSphere and performs the work. */ public void service(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException { //************************************************************************ // set content type, get print writer //************************************************************************ res.setContentType("text/html"); PrintWriter out = res.getWriter(); //************************************************************************ // write HTML page header //************************************************************************ out.println("<html>"); out.println("<head>"); out.println("<title>JDBC Parts Servlet</title>"); out.println("</head>"); out.println("<body>"); try { //******************************************************************* // load native iSeries 400 JDBC driver, get connection //******************************************************************* Class.forName("com.ibm.db2.jdbc.app.DB2Driver"); Connection conn = DriverManager.getConnection("jdbc:db2://*LOCAL"); //******************************************************************* // set / prepare SQL statement //******************************************************************* String sql = "SELECT * FROM APILIB.PARTS ORDER BY PARTNO"; PreparedStatement stmt = conn.prepareStatement(sql); //******************************************************************* // write table headers //******************************************************************* out.println("<table border=\"1\""); out.println("<tr>"); out.println("<td>PARTNO</td>"); out.println("<td>PARTDS</td>"); out.println("<td>PARTQY</td>"); out.println("<td>PARTPR</td>"); out.println("<td>PARTDT</td>"); out.println("</tr>");
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
31
//******************************************************************* // execute query, process each row //******************************************************************* ResultSet rs = stmt.executeQuery(); while (rs.next()) { out.println("<tr>"); out.println("<td>" + rs.getInt("PARTNO") out.println("<td>" + rs.getString("PARTDS") out.println("<td>" + rs.getInt("PARTQY") out.println("<td>" + rs.getBigDecimal("PARTPR") out.println("<td>" + rs.getDate("PARTDT") out.println("</tr>"); } rs.close(); conn.close(); } catch (Exception e) { out.println("Exception: " + e); e.printStackTrace(); } //************************************************************************ // write end of HTML page //************************************************************************ out.println("</table>"); out.println("</body>"); out.println("</html>"); out.close(); } } + + + + + "</td>"); "</td>"); "</td>"); "</td>"); "</td>");
Go to the "Downloads" area of the site and look for the WebSphere and VisualAge for Java section.
Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie
32