Creating and deploying DataSource objects
JDBC versions starting with version 2.0 provide the DataSource interface for connecting to a data source. Using the DataSource interface is the preferred way to connect to a data source.
About this task
Using the DataSource interface involves
two parts:
- Creating and deploying DataSource objects. This is usually done by a system administrator, using a tool such as WebSphere® Application Server.
- Using the DataSource objects to create a connection. This is done in the application program.
The IBM® Data Server Driver for JDBC and
SQLJ provides
the following DataSource implementations:
- com.ibm.db2.jcc.DB2SimpleDataSource, which does not support connection pooling. You can use this implementation with IBM Data Server Driver for JDBC and SQLJ type 2 connectivity or IBM Data Server Driver for JDBC and SQLJ type 4 connectivity.
- com.ibm.db2.jcc.DB2ConnectionPoolDataSource, which supports connection pooling. You can use this implementation with IBM Data Server Driver for JDBC and SQLJ type 2 connectivity or IBM Data Server Driver for JDBC and SQLJ type 4 connectivity.
- com.ibm.db2.jcc.DB2XADataSource, which supports connection pooling and distributed transactions. The connection pooling is provided by WebSphere Application Server or another application server. You can use this implementation only with IBM Data Server Driver for JDBC and SQLJ type 4 connectivity.
Procedure
To create and deploy a DataSource object, you need to perform these tasks:
- Create an instance of the appropriate DataSource implementation.
- Set the properties of the DataSource object.
- Register the object with the Java Naming and Directory Interface (JNDI) naming service.
Example
The following example shows how to perform these tasks.
import java.sql.*; // JDBC base
import javax.naming.*; // JNDI Naming Services
import javax.sql.*; // Additional methods for JDBC
import com.ibm.db2.jcc.*; // IBM Data Server Driver for
// JDBC and SQLJ
// implementation of JDBC
// standard extension APIs
DB2SimpleDataSource dbds = new com.ibm.db2.jcc.DB2SimpleDataSource(); 1
dbds.setDatabaseName("db2loc1"); 2
dbds.setDescription("Our Sample Database");
dbds.setUser("john");
dbds.setPassword("mypw");
…
Context ctx=new InitialContext(); 3
Ctx.bind("jdbc/sampledb",dbds); 4
Note | Description |
---|---|
1 | Creates an instance of the DB2SimpleDataSource class. |
2 | This statement and the next three statements set values for properties of this DB2SimpleDataSource object. |
3 | Creates a context for use by JNDI. |
4 | Associates DBSimple2DataSource object dbds with the logical name jdbc/sampledb. An application that uses this object can refer to it by the name jdbc/sampledb. |