Connecting To A Data Source Using The Drivermanager Interface With The Ibm Data Server Driver For Jdbc And Sqlj - IBM DB2 Manual

Table of Contents

Advertisement

Related concepts
"Example of a simple JDBC application" on page 7
Related tasks
"Connecting to a data source using SQLJ" on page 103
"Disconnecting from data sources in JDBC applications" on page 99
Connecting to a data source using the DriverManager
interface with the IBM Data Server Driver for JDBC and SQLJ
A JDBC application can establish a connection to a data source using the JDBC
DriverManager interface, which is part of the java.sql package.
The steps for establishing a connection are:
1. Load the JDBC driver by invoking the Class.forName method.
If you are using JDBC 4.0, you do not need to explicitly load the JDBC driver.
For the IBM Data Server Driver for JDBC and SQLJ, you load the driver by
invoking the Class.forName method with the following argument:
com.ibm.db2.jcc.DB2Driver
For compatibility with previous JDBC drivers, you can use the following
argument instead:
COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver
The following code demonstrates loading the IBM Data Server Driver for JDBC
and SQLJ:
try {
// Load the IBM Data Server Driver for JDBC and SQLJ with DriverManager
Class.forName("com.ibm.db2.jcc.DB2Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
The catch block is used to print an error if the driver is not found.
2. Connect to a data source by invoking the DriverManager.getConnection
method.
You can use one of the following forms of getConnection:
getConnection(String url);
getConnection(String url, user, password);
getConnection(String url, java.util.Properties info);
For IBM Data Server Driver for JDBC and SQLJ type 4 connectivity, the
getConnection method must specify a user ID and password, through
parameters or through property values.
The url argument represents a data source, and indicates what type of JDBC
connectivity you are using.
The info argument is an object of type java.util.Properties that contains a set
of driver properties for the connection. Specifying the info argument is an
alternative to specifying property=value; strings in the URL. See "Properties for
the IBM Data Server Driver for JDBC and SQLJ" for the properties that you can
specify.
There are several ways to specify a user ID and password for a connection:
v Use the form of the getConnection method that specifies url with
property=value; clauses, and include the user and password properties in the
URL.
v Use the form of the getConnection method that specifies user and password.
Chapter 3. JDBC application programming
11

Hide quick links:

Advertisement

Table of Contents
loading

Table of Contents