Sunteți pe pagina 1din 34

Using JDBC with iSeries WebSphere Applications

Craig Pelkie Bits & Bytes Programming, Inc. craig@web400.com

Using JDBC with iSeries WebSphere Applications


Edition JDBCWAS_20011002

Published by Bits & Bytes Programming, Inc. Valley Center, CA 92082 craig@web400.com

Copyright 2001, Craig Pelkie. All Rights Reserved


No part of this presentation or the accompanying computer source code may be reproduced or distributed in any form or by any means, or stored in a database or data retrieval system, without the prior written permission of Craig Pelkie, who is the author of the presentation and the computer source code. All computer source code distributed with this presentation, either on diskettes, CD-ROM, or available for downloading from sources such as the Internet is Copyright 2001 Craig Pelkie, All Rights Reserved. The source code is for use in computer programs that you develop for internal use within your company, or for use within programs that you develop for the use of your clients, when such programs are compiled and distributed in an executable computer program such that no part of the source code is readily visible without the aid of a computer program disassembler. No part of the computer source code distributed with this presentation shall be reproduced in source code format, either printed or in electronic format, by you or by others who you allow to have access to the source code. You shall not cause the source code to be stored on any information retrieval system, such as computer Bulletin Board Systems or the Internet. You shall not develop any written articles, books, seminar materials, or other presentations that include the source code provided on the diskettes accompanying this manual or within the manual itself. For any questions regarding your rights and responsibilities using the computer source code distributed with this presentation, contact Craig Pelkie, Bits & Bytes Programming, Inc., who is the owner of the source code.

LIMITATION OF LIABILITY AND DISCLAIMER OF WARRANTY


No representation is made that any of the programs, computer source code, commands, or configurations described and depicted in this manual and on the computer source code accompanying this presentation are error-free and suitable for any application that you may develop. Craig Pelkie makes no warranty of any kind, expressed or implied, including the warranties of merchantability or fitness for a particular purpose, with regard to the information, examples, and computer source code presented in this presentation and on the accompanying diskettes. Everything provided in this manual and on the accompanying diskettes is provided as is. Craig Pelkie shall not be liable in any event for incidental or consequential damages or any other claims, pursuant to your use of any of the techniques presented in this presentation, or your use of the computer source code in programs that you develop, even if Craig Pelkie has been advised of the possibility of such damages. You are responsible for testing any and all programs, configurations, commands, and procedures presented in this manual prior to using the programs, configurations, commands, and procedures with important user data. You must ensure that adequate and sufficient backup of important user data is available, in the event that recovery of the important user data is required.

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

The need for JDBC


Java programs can run on any platform with appropriate JVM Need to be able to access different databases Standard database access: SQL Standard technique for using SQL in Java: JDBC
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

The need for JDBC


The Java programming language is a great advance over most other programming languages, as a Java program that runs on one platform can usually be ported to another platform and run with no or minor changes. That is made possible by the presence of a compliant Java Virtual Machine (JVM) on the alternate platform. A "compliant JVM" is one that has passed the Sun Microsystems suite of tests to ensure that the JVM provides all of the required support for the level of the JVM. Most business applications require access to one or more databases. It is possible to use techniques to provide "native" access to the database, for example, the IBM AS/400 Toolbox for Java includes classes for record-level access. Those classes closely mimic the types of file I/O operations that iSeries 400 programmers are accustomed to using. However, if you write a Java program using those classes, you have then bound your program to run only against an iSeries 400 database. Although many iSeries 400 shops believe that they will only ever host their database on the iSeries, other shops need to be able to run their applications regardless of the database used. The industry standard technique for database access is SQL. You can develop iSeries 400 Java applications that use SQL by using JDBC. You do not need to have the chargeable Licensed Program Product DB2 Query Manager and SQL Developer's Kit (5722-ST1) installed on your iSeries 400 to develop and use Java programs with JDBC. As explained in the definitive reference about JDBC, JDBC API Tutorial and Reference (Second Edition), Sun Microsystems, ISBN 0-201-43328-1 (page 13), ...(a)s a point of interest, JDBC is the trademarked name and is not an acronym; nevertheless, JDBC is often thought of as standing for Java Database Connectivity.

Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie

About JDBC Drivers


Usually provided by database vendor (IBM, Oracle, Sybase, others not Microsoft) iSeries 400
EBCDIC / Unicode Packed / Zoned Authentication Special features of DB2 for iSeries
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

About JDBC Drivers


A JDBC driver is usually provided with a database product by the database vendor (as they have the greatest incentive to make it possible for applications to be developed that use their product). There are also third-party vendors that provide JDBC drivers. Sun Microsystems, Inc. provides this web page that you can use to search for JDBC drivers for different database products:
http://industry.java.sun.com/products/jdbc/drivers

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.

Features required for an iSeries JDBC driver


Among the features that an iSeries JDBC driver must support are the following:

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 2 Native API


Tied to specific platform; not portable AS/400 Native Driver is Type 2

Type 3 JDBCNet
pure Java to middleware to DB

Type 4 Native protocol


Sockets connection to DB AS/400 Toolbox for Java is Type 4
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

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.

Type 1 JDBCODBC Bridge


This type of JDBC driver works with an ODBC driver. Many of the early JDBC drivers were Type 1 drivers, as they could use the existing ODBC driver to provide access to the underlying database.

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

Type 2 Native API


JDBC drivers of this type use native API calls (typically written in C or C++) to access the underlying database. As such, the driver needs to be installed on the host machine. The JDBC requests issued by your Java application are passed to the driver and translated into the native API calls to the database. The iSeries 400 native JDBC driver is a Type 2 driver.

Benefits

Typically highly optimized for the underlying database.

Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie

Contained/controlled deployment, must be installed (usually as part of an operating system install).

Drawbacks

Must be installed on the host machine. May be tied to a particular level of the operating system or database.

Type 3 JDBC Net


Drivers of this type translate JDBC calls on the client into a network protocol of the vendors' choosing. The network protocol is then translated into specific requests of the database by a server program that receives the network protocol. For example, JDBC requests might be translated into XML, sent to a server over HTTP, and translated on the server from XML into native database requests.

Benefits

Most flexible type of driver.

Type 4 Native Protocol


A native protocol JDBC driver sends JDBC calls from the client directly to the database using a TCP/IP sockets connection. The iSeries 400 Toolbox for Java JDBC driver is this type of driver (it uses the same Host Server support as is used by the IBM Client Access for iSeries 400 product). Note: the IBM Client Access for iSeries 400 product is not required to use the Toolbox for Java JDBC driver.

Benefits

Provides direct path from other machines to the database server.

Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie

AS/400 JDBC Drivers


AS/400 Developer Kit for Java (5722-JV1)
Supports Local database access JDBC driver class:
com.ibm.db2.jdbc.app.DB2Driver

URL for access:


jdbc:db2://<database> jdbc:jta:db2://<database>

where <database> is RDB name or *LOCAL


Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

AS/400 JDBC Drivers


AS/400 Toolbox for Java (5722-JC1)
Supports remote database access JDBC driver class:
com.ibm.as400.access.AS400JDBCDriver

URL for access:


jdbc:as400://system,UID,PWD

where system is AS/400 system name


Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

iSeries 400 JDBC Drivers


IBM provides two no-charge JDBC drivers with the iSeries 400. The drivers are provided in the AS/400 Developer Kit for Java Licensed Program Product (LPP) and the AS/400 Toolbox for Java LPP. Both of those LPPs are non-chargeable features available with a standard OS/400 order.

Developer Kit for Java driver


This driver is the "Type 2" driver. It is installed on the iSeries 400 and is used by Java programs running on that server to access the local database or another database that can be located through the Relational Database Directory Entries on the iSeries 400 (see the Work with Relational Database Directory Entries command, WRKRDBDIRE). This is the driver that will typically be used in WebSphere Application Server programs that run on the iSeries 400.

Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie

Specifying the class


To use this JDBC driver, use the following statement in your Java program:
Class.forName("com.ibm.db2.jdbc.app.DB2Driver")

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.

URL for access


The URL used with this driver is specified using one of the following formats:
jdbc:db2://<database_name> jdbc:jta:db2://<database_name>

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.

Toolbox for Java


This driver is initially installed on the iSeries 400 system, but is then usually exported to or installed on other systems that will access the iSeries 400 database. The Toolbox for Java is contained in the file jt400.jar, which by default is installed in the iSeries 400 Integrated File System (IFS) in directory:
\QIBM\ProdData\HTTP\Public\jt400\lib

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

Specifying the class


To use this JDBC driver, use the following statement in your Java program:
Class.forName("com.ibm.as400.access.AS400JDBCDriver")

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.

URL for access


The URL used with this driver is specified using one of the following formats:
jdbc:as400://<system_name> jdbc:as400://<tcpip_address>

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

Running the Toolbox driver on the same iSeries 400


If you develop a Java application that initially runs remotely (for example, develop/test in VisualAge for Java on a PC workstation using the Toolbox for Java JDBC driver), and then export the application to the iSeries 400 server, you should change the JDBC driver and URL for access to use the native JDBC driver. If you forget to change the driver and URL, your application will still run, assuming that the Toolbox for Java classes can be found in the classpath of your server application. However, the Toolbox for Java JDBC driver always makes a TCP/IP sockets connection to the database through the Host Servers. This is not as efficient as the native driver, which issues native API calls to the iSeries 400 database. If you develop WebSphere applications, you can avoid this problem by always using a datasource object, rather than directly instantiating the JDBC class in your Java programs. Another alternative is to "soft-code" the class name and URL parameters and pass them into your Java class at run-time.

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

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

JDBC Objects and their relationships


A JDBC application typically uses five objects that work with each other. The objects are usually created in a specific order, as there are dependencies among the objects.

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

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

The java.sql package


The classes, interfaces and exceptions that are used with JDBC are provided in the java.sql package, which is a standard part of the Java Development Kit (JDK). If you use IBM VisualAge for Java, the java.sql package is located in the Java class libraries project, which is automatically installed in VisualAge for Java. You will usually code the import java.sql.*; statement as one of the first statements in your classes that use JDBC. Once you code that statement, you can refer to the JDBC classes and interfaces by their class or interface name, rather than the fully qualified package name. Note: import does not copy code into your class. The import statement in Java is used as a shortcut to help you refer to classes in a package. For example, the package java.sql contains the classes Connection and Statement to work with SQL connections and statements. If you dont include the import java.sql.*; statement, you need to specify the full class names as follows:
java.sql.Connection java.sql.Statement

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

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

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.*;

Some of the commonly used interfaces in the javax.sql package are:

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

Using JDBC Load Driver


Use Class.forName
Class.forName(com.ibm.as400.access.AS400JDBCDriver);

JDBC driver class must be in classpath Class.forName


Locates JDBC driver Loads it Registers with DriverManager
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

Using JDBC Load the driver


Before you can use a JDBC driver in your application, you need to load it. Loading the driver makes it known to the driver manager, which is responsible for providing the environment for your application to connect to a database.

Two techniques to load the driver


There are two generally used techniques to load the JDBC driver:
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver()); Class.forName("com.ibm.as400.access.AS400JDBCDriver");

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.

Which driver to load


You must select a driver to load based on where your Java program is running and where the database you need to access is located:

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

Using JDBC get connection


DriverManager.getConnection
returns Connection object use connection URL to identify
JDBC driver / server / properties Properties control driver processing
Connection conn = DriverManager.getConnection( jdbc:as400://as400_name/library); Connection conn = DriverManager.getConnection( jdbc:db2://*LOCAL);
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

10

Using JDBC get a connection


After the JDBC driver is loaded, you can get a connection to the database from your program. The database can be local (on the same iSeries 400 that your Java program is running on) or remote (for example, your Java application is running on another machine and needs to access an iSeries 400 database).

The connection URL


You use the DriverManager.getConnection method to create a connection object to a specific iSeries 400 database. The getConnection method uses a connection URL to identify which JDBC driver to use and the location of the database.

Connection URL for the Native driver


The connection URL is specified as follows:
jdbc indicates that the JDBC protocol is being used. db2 the subprotocol, used by the DriverManager class to locate the iSeries 400 native JDBC driver (com.ibm.db2.jdbc.app.DB2Driver). *LOCAL refers to the Relational Database Directory Entry name for the database located on

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

Connection URL for the Toolbox driver


The connection URL is specified as follows:
jdbc indicates that the JDBC protocol is being used. as400 the subprotocol, used by the DriverManager class to locate the iSeries 400 Toolbox JDBC driver (com.ibm.as400.access.AS400JDBCDriver). //as400_name refers to the TCP/IP host name or TCP/IP address of the iSeries 400 server.

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

the library name, you can specify it in your SQL statements.

Specifying the User ID and Password


If you don't supply an iSeries 400 user ID and password as part of your JDBC connection, the user ID of the WebSphere Application Server is used (by default, user profile QEJBSVR). If the QEJBSVR user profile has sufficient authority to the database objects, your SQL statements will run. If you need to specify a different user ID and password, you can include the user ID and password as parameters to the getConnection method, or you can put the values into a Properties object and pass that object to the JDBC driver on the getConnection method.

Supply the user ID and password


Connection conn = DriverManager.getConnection("jdbc:db2://*LOCAL", "userID", "password");

Supply the user ID and password in a Properties object


Properties prop = new Properties(); prop.put("user", "userID_value"); prop.put("password", "password_value"); Connection conn = DriverManager.getConnection("jdbc:db2://*LOCAL", prop);

Setting JDBC driver properties


You can set properties for the JDBC driver either as part of the connection URL or in a properties object. For example, to enable tracing and full error reporting, you can use either of these techniques:

Properties passed on URL


Connection conn = DriverManager.getConnection("jdbc:db2://*LOCAL;trace=true;errors=full");

Properties passed in Properties object


Properties prop = new Properties(); prop.put("trace", "true"); prop.put("errors", "full"); Connection conn = DriverManager.getConnection("jdbc:db2://*LOCAL", prop);

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

Using JDBC create statement


conn.createStatement
returns Statement object

PreparedStatement
performance (precompile statement) use variable parameters in statement

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

11

Using JDBC create a statement


Once you have a valid connection object, you can use it to create one or more statement objects. A statement object is used to pass an SQL statement from your Java program to the database. The JDBC driver does not check your SQL statement for validity; it simply passes it through. If there are any syntactical or execution errors with the statement, the SQL errors are returned to your Java program as a series of one or more SQLException objects.

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

Using JDBC prepared statements

Problem how to provide run-time values to SQL statement


Build statement dynamically (concat)
Each statement must then be parsed

Prepare statement with parameter markers


Statement can be parsed / stored Parameter values inserted just in time
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

12

Using JDBC prepared statements


Most SQL SELECT statements are run with different selection or ordering criteria, depending upon user input. Similarly, INSERT, UPDATE and DELETE statements also use different values, depending upon which rows in the table should be affected. One way to create an SQL statement with variables is to build it up by character string concatenation operations:
String sql = "select * from parts where partno=" + request.getParameter("PARTNO")

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

Using JDBC resultset


Returned from executeQuery on statement object Default resultset is
Read-only Nonscrollable (read forward only)

Returned before first row


use rs.next to get first, next rows

Use get methods to get column values


Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

13

Using JDBC resultset


When you run an SQL SELECT statement, you usually expect the server to return one or more rows from the table to your program. The object used to return data to you is the result set. A result set is returned even if no rows were selected from the table. A result set is conceptually like a spreadsheet, with rows and columns of data. If there are any rows of data returned from a table, the returned rows start with the first row in the result set (that is, there is not a "column heading" row). If you need to retrieve the column heading values, you can use the result set metadata object which is created and returned to your program along with the result set. For most applications, you will not need to use result set metadata, since you will know in advance what columns will be contained in your result set. The result set uses a cursor to determine which row to work with. Although SQL returns a "set" of data, you navigate through the result set one row at a time. When the result set is returned to you, the cursor is positioned before the first row, if any, in the result set. You will usually see result set navigation code written like this:
while (rs.next()) { int dbPartno = rs.getInt("PARTNO"); String dbPartds = rs.getString("PARTDS"); }

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

Using JDBC update database


Use stmt.executeUpdate method
Supports all SQL statements other than SELECT Does not return a resultset

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

14

Using JDBC update the database

Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie

20

Database access no connection pool


1. Request for database services 2. Servlet creates unique connection

3. Request is processed 4. Connection closed, discarded

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

15

Database access with connection pool


1. WAS starts, creates connection pool 3. Next available connection assigned to request Conn Pool 4. Request is processed 5. Connection closed, released back to pool

2. Request for database services

Using JDBC with WebSphere


Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

16

JDBC and Connection Pool

Using JDBC with iSeries WebSphere Applications Copyright 2001, Craig Pelkie

21

Configuring Connection Pools


Define JDBC driver Create Datasource, associated JDBC driver with it Assign properties to datasource:
size Minimum pool size Maximum pool size Connection timeout request waits for connection to become available Idle timeout seconds until connection is closed Orphan timeout connection holder holds but does not use connection
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

17

Configuring a Connection Pool

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

Figure 2: You can "create" a new JDBC driver.

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

JDBC / Connection Pool Code


Iterative development
First pass: VA Java, no connection pool, results viewed in VA Java console Second pass: Recode as servlet, no connection pool, configure in WAS, view in browser Third pass: Recode servlet to use connection pool, view in browser
Using JDBC with WebSphere
Copyright 2001. Craig Pelkie ALL RIGHTS RESERVED

23

JDBC / Connection Pool Code


First pass: VA Java, Console output
The first pass is a "proof of concept" to establish that the correct JDBC code is being used to get the intended results: a listing of data in the PARTS table. The output is sent to the VisualAge for Java Console window. Because the code is running on the development workstation, the iSeries 400 Toolbox for Java (the "remote") JDBC driver is used. That driver makes a TCP/IP network connection to the iSeries 400 and sends the SQL statement to the database. Because an iSeries 400 user ID and password is not provided in the Java code, the Toolbox for Java displays the "sign-on" prompt window and uses that to get the user ID and password. The value of developing the code in this environment is that it is very easy to debug and make changes. If the results are correct, it is not difficult to change this program from a stand-alone Console output program to a servlet.

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

import import import import

com.ibm.as400.access.*; java.io.*; java.sql.*; java.util.*;

/** * 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); } }

System.out.println("Before rs.close"); rs.close(); conn.close();

Second pass: recode as a servlet


In this pass, the code from the Console output is recoded as a servlet. The primary difference between the two programs is that the servlet output is directed to an HTTP data stream provided by WebSphere Application Server, rather than simply being sent to the Console. Once the code is developed on the workstation, it is exported from VisualAge for Java to the WebSphere directory in the iSeries 400 Integrated File System (IFS). At that point, the servlet needs to be configured in WebSphere and the web application contains the servlet must be restarted. The servlet is then requested in the browser, with the output shown below. In the sample code, the JDBC driver is set to the native driver. The iSeries 400 user ID and password are not passed in to the servlet, so the default WebSphere user profile for the job is used (user profile QEJBSVR).

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

import import import import import

java.io.*; java.sql.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

/** * 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>");

Third pass: recode to use connection pool


You can view the sample code for connection pool processing for this application at:
http://www.web400.com

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

S-ar putea să vă placă și