IBM DB2 Manual page 32

Table of Contents

Advertisement

The best way to use a DataSource object is for your system administrator to create
and manage it separately, using WebSphere Application Server or some other tool.
The program that creates and manages a DataSource object also uses the Java
Naming and Directory Interface (JNDI) to assign a logical name to the DataSource
object. The JDBC application that uses the DataSource object can then refer to the
object by its logical name, and does not need any information about the underlying
data source. In addition, your system administrator can modify the data source
attributes, and you do not need to change your application program.
To learn more about using WebSphere to deploy DataSource objects, go to this
URL on the Web:
http://www.ibm.com/software/webservers/appserv/
To learn about deploying DataSource objects yourself, see "Creating and deploying
DataSource objects".
You can use the DataSource interface and the DriverManager interface in the same
application, but for maximum portability, it is recommended that you use only the
DataSource interface to obtain connections.
To obtain a connection using a DataSource object that the system administrator has
already created and assigned a logical name to, follow these steps:
1. From your system administrator, obtain the logical name of the data source to
2. Create a Context object to use in the next step. The Context interface is part of
3. In your application program, use JNDI to get the DataSource object that is
4. Use the DataSource.getConnection method to obtain the connection.
Example of obtaining a connection using a DataSource object that was created by the
system administrator: In this example, the logical name of the data source that you
need to connect to is jdbc/sampledb. The numbers to the right of selected
statements correspond to the previously-described steps.
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
...
Context ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb"); 3
Connection con=ds.getConnection();
Figure 4. Obtaining a connection using a DataSource object
Example of creating and using a DataSource object in the same application:
Figure 5. Creating and using a DataSource object in the same application
16
Application Programming Guide and Reference for Java
which you need to connect.
the Java Naming and Directory Interface (JNDI), not JDBC.
associated with the logical data source name.
You can use one of the following forms of the getConnection method:
getConnection();
getConnection(String user, String password);
Use the second form if you need to specify a user ID and password for the
connection that are different from the ones that were specified when the
DataSource was deployed.
2
4

Hide quick links:

Advertisement

Table of Contents
loading

Table of Contents