BEA Logo BEA WebLogic Server Release 1.1

  Corporate Info  |  News  |  Solutions  |  Products  |  Partners  |  Services  |  Events  |  Download  |  How To Buy

Using a DataSource object to get a JDBC connection



Import statements

Setting up WebLogic Server to use a DataSource

Obtaining a client connection using DataSource

Code examples


A DataSource object provides a new way for JDBC clients to obtain a DBMS connection. To create a DataSource object you define it with an entry in the file. This DataSource entry then points to a connection pool that is also defined in the file.

DataSource objects can be defined with or without Java Transaction Services (JTS) enabled. Creating a DataSource object with JTS enabled causes the connection to behave like a JTS connection, with support for transactions.

Import statements

To use the DataSource objects, import the following classes in your client code:

import java.sql.*;
import java.util.*;
import javax.naming.*;

Setting up WebLogic Server to use a DataSource

  1. Define a DataSource in the file.

    To define a JTS-enabled DataSource named "myJtsDataSource" for the connection pool "myConnectionPool", add the following line to the file:


    To define a DataSource named "myNonJtsDataSource" for the connection pool "myConnectionPool" that is not JTS-enabled, add the following line to the file:


    You can define multiple DataSources that use a single connection pool. This allows you to define both JTS-enabled and non-JTS-enabled DataSource objects that share the same database.

  2. Define a connection pool by adding the following to the file:


    (The example above shows a connection pool to an Oracle database, using WebLogic jDriver for Oracle. Substitute the URL and class name--shown in italics--of the JDBC driver you will be using to connect to your DBMS)

Obtaining a client connection using DataSource

To obtain a connection from a JDBC client, use a Java Naming and Directory Interface (JDNI) look up to locate the DataSource object, as shown in this code fragment:

Context ctx = null;
Hashtable ht = new Hashtable();

  try {
ctx = new InitialContext(ht);
javax.sql.DataSource ds
= (javax.sql.DataSource) ctx.lookup ("myJtsDataSource");
java.sql.Connection conn = ds.getConnection();

// You can now use the conn object to create 
// Statements and retrieve result sets:

Statement stmt = conn.createStatement();
stmt.execute("select * from someTable");
ResultSet rs = stmt.getResultSet();

// Close the statement and connection objects when you are finished:

catch (NamingException e) {
// a failure occurred
finally {
try {ctx.close();}
catch (Exception e) {
// a failure occurred

(Substitute the correct hostname and port number for your WebLogic Server.

Note: The code above use one of several available procedures for obtaining a JNDI context. For more information on JNDI, see Using WebLogic JNDI.

Code examples