BEA Home | Events | Solutions | Partners | Products | Services | Download | Developer Center | WebSUPPORT
| WebLogic Server Doc Home | Programming WebLogic JDBC | Previous Topic | Next Topic | Contents | View as PDF

Configuring WebLogic JDBC Features

The following sections describe how to program the JDBC connectivity components:

- Using Connection Pools

- Using MultiPools

- Configuring and Using DataSources

Using Connection Pools

A connection pool is a named group of identical JDBC connections to a database that are created when the connection pool is registered, usually when starting up WebLogic Server. Your application "borrows" a connection from the pool, uses it, then returns it to the pool by closing it. Also see Overview of Connection Pools.

Advantages to Using Connection Pools

Connection Pools provide numerous performance and application design advantages:

- Using Connection Pools is far more efficient than creating a new connection for each client each time they need to access the database.

- You do not need to hard-code details such as the DBMS password in your application.

- You can limit the number of connections to your DBMS. This can be useful for managing licensing restrictions on the number of connections to your DBMS.

- You can change the DBMS you are using without changing your application code.

The attributes for configuring a connection pool are defined in the Administration Console Online Help. There is also an API that you can use to programmatically create connection pools in a running WebLogic Server; see Creating a Connection Pool Dynamically. You can also use the command line; see the Web Logic Server Command-Line Interface Reference in the Administration Guide.

Connection Pool Fail-Over Requirements

WebLogic Server cannot provide fail-over for connections that fail while being used by an application. Any failure while using a connection requires that you restart the transaction and provide code to handle such a failure.

Creating a Connection Pool at Startup

You set attributes in the in the Administration Console to create a startup (static) connection pool. The WebLogic Server opens JDBC connections to the database during the startup process and adds the connections to the pool.

Here is a list with descriptions of the connection pool attributes. For more information see "Managing JDBC Connectivity" in the Administration Guide and the Administration Console Online Help.

Connection Pool Attributes

  Name

  (Required) Name of the connection pool. You use the name to access a JDBC Connection from this pool.

  URL

  (Required) URL of the JDBC 2-tier driver for the connection between the WebLogic Server and the DBMS. You can use one of the WebLogic jDrivers or another JDBC driver that you have tested in a 2-tier environment. Check the documentation for the JDBC driver you choose to find the URL.

  Driver Class Name

  (Required) Full package name of the JDBC 2-tier driver class for the connection between the WebLogic Server and the DBMS. Check the documentation for the JDBC driver to find the full pathname.

  Properties

  (Required) The properties for connecting to the database, such as username, server, and open string for XA connections. For the database password, use the Password property. For the password in the open string, use the Open String Password attribute.

  The properties are defined by, and processed by, the two-tier JDBC driver that you use. Check the documentation for the JDBC driver to find the properties required to connect to your DBMS.

  Password

  (Optional) The database password passed to the 2-tier JDBC driver when creating physical database connections. This value overrides any database password defined in the Properties attribute (as a name/value pair). The value is stored in an encrypted form in the config.xml file.

  Open String Password

  (Optional) The password is used in the open string for creating an XA physical database connection. This value overrides the password in the open string defined in the Properties attribute. The value is stored in an encrypted form in the config.xml file.

  Login Delay Seconds

  (Optional) Number of seconds to wait between each attempt to open a connection to the database. Some database servers can't handle multiple requests for connections in rapid succession. This property allows you to build in a small delay to let the database server catch up.

  Initial Capacity

  (Optional) The initial size of the pool. If this value is unset, the default is the value you set for CapacityIncrement.

  Maximum Capacity

  (Required) The maximum size of the pool.

  Capacity Increment

  The size by which the pool's capacity is enlarged. Initial Capacity and Capacity Increment work somewhat like a Java Vector, which has an initial allocation (its "capacity") and is increased in increments as necessary (capacityIncrement), up to the pool Maximum Capacity. The default value is 1.

  Allow Shrinking

  (Optional) Whether this connection pool should be allowed to shrink back to its initial capacity, after expanding to meet increased demand. Set Shrink Period if this property is set to true, or it will default to 15 minutes. Note that Allow Shrinking is set by default to false, for backwards compatibility.

  Shrink Period

  (Optional) The number of minutes to wait before shrinking a connection pool that has incrementally increased to meet demand. The default shrink period is 15 minutes and the minimum is 1 minute.

Note: If you set a value for this attribute when AllowShrinking is set to false, WebLogic Server ignores the false setting and allows shrinking according to the value in ShrinkPeriodMins.

  Test Table Name

  (Required only if you set Refresh Period, T est Reserved Connections, or Test Released Connections.) The name of a table in the database that is used to test the viability of connections in the connection pool. The query select count(*) from Test Table Name is used to test a connection. The Test Table Name must exist and be accessible to the database user for the connection. Most database servers optimize this SQL to avoid a table scan, but it is still a good idea to set Test Table Name to the name of a table that is known to have few rows, or even no rows.

  Refresh Period

  (Optional) This property, together with the Test Table Name property, enables autorefresh of connections in the pools. At a specified interval, each unused connection in the connection pool is tested by executing a simple SQL query on the connection. If the test fails, the connection's resources are dropped and a new connection is created to replace the failed connection. The default value is 0.

  To enable autorefresh, set Refresh Period to the number of minutes between connection test cycles—a value greater than or equal to 0. If you set an invalid Refresh Period value, the value defaults to 5 minutes. Set Test Table Name to the name of an existing database table to use for the test (required).

  Also see Notes About Refreshing Connections in a JDBC Connection Pool.

  Test Reserved Connections

  (Optional) When set to true, the WebLogic Server tests a connection after removing it from the pool and before giving it to the client. The test adds a small delay in serving the client's request for a connection from the pool, but ensures that the client receives a working connection (assuming that the DBMS is available and accessible). The Test Table Name parameter must be set to use this feature.

  When using a connection pool in a MultiPool with the High Availability algorithm, you must set this attribute to true so that the MultiPool can determine when to fail over to the next connection pool in the list. See MultiPool Fail-Over Limitations and Requirements.

  Test Released Connections

  (Optional) When set to true, the WebLogic Server tests a connection before returning it to the connection pool. If all connections in the pool are already in use and a client is waiting for a connection, the client's wait will be slightly longer while the connection is tested. The Test Table Name parameter must be set to use this feature.

Notes About Refreshing Connections in a JDBC Connection Pool

When the refresh process finds a bad database connection that it cannot replace, the process stops its current cycle. It does not delete remaining broken connections from the connection pool. They remain in the connection pool until they can be replaced by new connections. This behavior was designed to avoid degrading performance by using system cycles to refresh database connections when the DBMS is inaccessible.

The refresh process cannot test or refresh connections currently being used by application code. It will only test connections that are not currently reserved. Thus a refresh cycle, even if it is able to replace any bad connections it finds, may never test all connections in the connection pool if applications are requesting connections.

Because the refresh process can only test connections not in use, it's possible that some connections will never be tested. A client will always run the risk of getting a broken connection unless testConnsOnReserve is enabled. In fact, even if the connection is tested before being given to an application, the connection could go bad immediately after the successful test.

Permissions

Set the permissions for creating dynamic connection pools in the Administration Console.You associate an ACL with a dynamic connection pool when you create the connection pool. The ACL and connection pool are not required to have the same name, and more than one connection pool can make use of a single ACL. If you do not specify an ACL, the "system" user is the default administrative user for the pool and any user can use a connection from the pool.

If you define an ACL for connection pools, access is restricted to exactly what is defined in the ACL. For example, before you have any ACLs for connection pools in your fileRealm.properties file, everyone has unrestricted access to all connection pools in your domain. However, if you add the following line to the file, access becomes very restricted:

>     acl.reset.weblogic.jdbc.connectionPool=Administrators

This line grants reset privileges to Administrators on all connection pools and it prohibits all other actions by all other users. By adding an ACL, file realm protection for connection pools is activated. WebLogic Server enforces the ACLs defined in fileRealm.properties and only allows access specifically granted in the file. If your intent in adding the ACL was to restrict resets only on connection pools, you must specifically grant privileges for other actions to everyone or to specific roles or users. For example:

>     acl.reserve.weblogic.jdbc.connectionPool=everyone
>     acl.shrink.weblogic.jdbc.connectionPool=everyone
>     acl.admin.weblogic.jdbc.connectionPool=everyone

Table 4-1 lists the ACLs that you can use in fileRealm.properties to secure connection pools.

Table 4-1 File Realm JDBC ACLs

Use this ACL. . . | To Restrict. . .
--- | ---
reserve.weblogic.jdbc.connectionPool[.poolname] | Reserving connections in a connection pool.
reset.weblogic.jdbc.connectionPool[.poolname] | Resetting all the connections in a connection pool by shutting down and reestablishing all allocated connections.
shrink.weblogic.jdbc.connectionPool[.poolname] | Shrinking the connection pool to its original size (number of connections).
admin.weblogic.jdbc.connectionPool[.poolname] | Enabling, disabling, and shutting down the connection pool.
admin.weblogic.jdbc.connectionPoolcreate | Creation of connection pools.

For information on how to modify ACLs, see Defining ACLs in the Managing Security section of the Administration Guide.

Connection Pool Limitation

When using connection pools, it is possible to execute DBMS-specific SQL code that will alter the database connection properties and that WebLogic Server and the JDBC driver will not be unaware of. When the connection is returned to the connection pool, the characteristics of the connection may not be set back to a valid state. For example, with a Sybase DBMS, if you use a statement such as set rowcount 3 select * from y, the connection will only ever return a maximum of 3 rows. When the connection is returned to the connection pool and then reused, the client will still only get 3 rows returned, even if the table they are selecting against has 500 rows. In most cases, there is standard (non-DBMS-specific) SQL code that can accomplish the same result and for which WebLogic Server or the JDBC driver will reset the connection. In this example, you could use setMaxRows() instead of set rowcount.

If you use DBMS-specific SQL code that alters the connection, you must set the connection back to an acceptable state before returning it to the connection pool.

Creating a Connection Pool Dynamically

A JNDI-based API allows you to create a connection pool from within a Java application. With this API, you can create a connection pool in a WebLogic Server that is already running. Access to dynamic connection pools requires a JTS or Pool driver.

Dynamic pools can be temporarily disabled, which suspends communication with the database server through any connection in the pool. When a disabled pool is enabled, the state of each connection is the same as when the pool was disabled; clients can continue their database operations right where they left off.

Properties

To define a specific property for your connection pool, be sure that you duplicate the key's exact spelling and case. You pair these types (keys) along with their values, shown in the table below, in a java.utils.Properties object that is used when creating the pool.

Table 4-2 Connection Pool Properties

Property Type | Description | Sample Property Value
--- | --- | ---
poolName | Required. Unique name of pool. | myPool
aclName | Required. Identifies the different access lists within fileRealm.properties in the server config directory. Paired name must be dynaPool. | dynaPool
props | Database connection properties; typically in the format "database login name; server network id". | user=scott; server=ora817
password | Optional. Database password passed to the 2-tier JDBC driver when creating physical database connections. This value overrides any database password defined in props (as a name/value pair). The value is stored in an encrypted form in the config.xml. | tiger
xapassword | Optional. Password is used in the open string for creating an XA physical database connection. This value overrides the password in the open string defined in props. The value is stored in an encrypted form in the config.xml. | secret
initialCapacity | Initial number of connections in a pool. If this property is defined and a positive number > 0, WebLogic Server creates these connections at boot time. Default is 0; cannot exceed maxCapacity. | 1
maxCapacity | Maximum number of connections allowed in the pool. Default is 1; if defined, maxCapacity should be =>1. | 10
capacityIncrement | Number of connections that can be added at one time. Default = 0. | 1
allowShrinking | Indicates whether or not the pool can shrink when connections are detected to not be in use. Default = true. | True
shrinkPeriodMins | Interval between shrinking. If allowShrinking = True, then default = 15 minutes. | 5
driver | Required. Name of JDBC driver. Only local (non-XA) drivers can participate. | weblogic.jdbc.oci.Driver
url | Required. URL of the JDBC driver. | jdbc:weblogic:oracle
testConnectionsOnReserve | Indicates reserved test connections. Default = False. | true
testConnectionsOnRelease | Indicates test connections when they are released. Default = False. | true
testTableName | Database table used when testing connections; must be present for tests to succeed. Required if testConnectionsOnReserve, testConnectionsOnRelease, or refreshPeriod is defined. | myTestTable
refreshPeriod | Interval between connection testing. | 1
loginDelaySecs | Seconds between each login attempt. Default = 0. | 1

Dynamic Connection Pool Sample Code

The following sample code shows how to create a connection pool programmatically.

Note: The following code samples cannot be used in a clustered environment. As a work-around, you can create connection pools and data sources in the Administration Console as described in the Administration Console Online Help, and target the connection pools and data sources to a cluster.

Import Packages

Import the following packages:

>     import java.util.Properties
>     import weblogic.common.*;
>     import weblogic.jdbc.common.JdbcServices;
>     import weblogic.jdbc.common.Pool;

Use JNDI to Retrieve the JdbcServices Object

The object reference allows you to access all the methods needed to create the dynamic pool. First, get an initial JNDI context to the WebLogic JNDI provider, and then look up "weblogic.jdbc.common.JdbcServices."

>     Hashtable env = new Hashtable();

>     env.put(Context.INITIAL_CONTEXT_FACTORY,
>              "weblogic.jndi.WLInitialContextFactory");
>     // URL for the WebLogic Server
>     env.put(Context.PROVIDER_URL, "t3://localhost:7001");
>     env.put(Context.SECURITY_PRINCIPAL, "Fred");
>     env.put(Context.SECURITY_CREDENTIALS, "secret");

>     Context ctx = new InitialContext(env);

>     // Look up weblogic.jdbc.JdbcServices
>     weblogic.jdbc.common.JdbcServices jdbc =
>      (weblogic.jdbc.common.JdbcServices)
>        ctx.lookup("weblogic.jdbc.JdbcServices");

Set the Properties

Set up the java.utils.properties object that defines the attributes of your pool. See Table 4-2 Connection Pool Properties in Properties

Once you have loaded weblogic.jdbc.JdbcServices, you pass the weblogic.jdbc.common.JdbcServices.createPool() method a Properties object that describes the pool. The Properties object contains the same properties you use to create a connection pool in the Administration Console, except that the "aclName" property is specific to dynamic connection pools.

The following example creates a connection pool named "eng2" for the DEMO Oracle database. The connections log into the database as user "SCOTT" with password "tiger." When the pool is created, one database connection is opened. A maximum of ten connections can be created on this pool. The "aclName" property specifies that the connection pool will use the "dynapool".

>     String thePoolName = "eng2";
>     Properties poolProps = null;
>     Pool myPool = null;
>     weblogic.jdbc.common.Pool pool = null

>     poolProps = new Properties();

>      // Set properties for the ConnectionPool.
>     poolProps.put("poolName", thePoolName);
>     poolProps.put("url", "jdbc:weblogic:oracle");
>     poolProps.put("driver", "weblogic.jdbc.oci.Driver");
>     poolProps.put("props", "user=scott;password=tiger;server=demo");
>     poolProps.put("password", "tiger");
>     poolProps.put("initialCapacity", "1");
>     poolProps.put("maxCapacity", "10");
>     poolProps.put("capacityIncrement", "1");
>     poolProps.put("aclName", "weblogic.jdbc.connectionPool.dynapool");
>     poolProps.put("allowShrinking", "true");
>     poolProps.put("shrinkPeriodMins", "5");
>     poolProps.put("refreshPeriod", "10");
>     poolProps.put("testConnectionsOnReserve", "true");
>     poolProps.put("testConnectionsOnRelease", "false");
>     poolProps.put("testTableName", "dual");
>     poolProps.put("loginDelaySecs", "1");

Create the Dynamic Pool

Create the pool by passing in the newly defined Properties object to the JdbcServices object previously retrieved from JNDI. An exception is thrown if there is a problem creating the pool, such as a new pool with the same name as an existing pool.

>     // create our pool

>             try {

>                 myJdbc.createPool(poolProps);
>             } catch (Exception e) {
>                 System.out.println(thePoolName
>                           + " can't be created ..");
>                 System.exit(666);
>             }

Retrieve the Pool Handle

Retrieve the pool handle from the newly created pool.You use the pool handle to manipulate the pool during the course of the application.

>             weblogic.jdbc.common.Pool myPool = null;

>             // get our pool, we would like to do something with it...

>          	try {

>                theNewPool = myJdbc.getPool(thePoolName);

>         	} catch (Exception e) {
>            	   System.out.println("Cannot retrieve pool: "
>                              +  thePoolName);
>                System.exit(666);

>             }

Managing Connection Pools

The weblogic.jdbc.common.Pool and weblogic.jdbc.common.JdbcServices interfaces provide methods to manage connection pools and obtain information about them. Methods are provided for:

- Retrieving information about a pool

- Disabling a connection pool, which prevents clients from obtaining a connection from it

- Enabling a disabled pool

- Shrinking a pool, which releases unused connections until the pool has reached the minimum specified pool size

- Refreshing a pool, which closes and reopens its connections

- Shutting down a pool

Retrieving Information About a Pool

  weblogic.jdbc.common.JdbcServices.poolExists()

  weblogic.jdbc.common.Pool.getProperties()

The poolExists() method tests whether a connection pool with a specified name exists in the WebLogic Server. You can use this method to determine whether a dynamic connection pool has already been created or to ensure that you select a unique name for a dynamic connection pool you want to create.

The getProperties() method retrieves the properties for a connection pool.

Disabling a Connection Pool

  weblogic.jdbc.common.Pool.disableDroppingUsers()

  weblogic.jdbc.common.Pool.disableFreezingUsers()

  weblogic.jdbc.common.pool.enable()

You can temporarily disable a connection pool, preventing any clients from obtaining a connection from the pool. Only the "system" user or users granted "admin" permission by an ACL associated with a connection pool can disable or enable the pool.

After you call disableFreezingUsers(), clients that currently have a connection from the pool are suspended. Attempts to communicate with the database server throw an exception. Clients can, however, close their connections while the connection pool is disabled; the connections are then returned to the pool and cannot be reserved by another client until the pool is enabled.

Use disableDroppingUsers() to not only disable the connection pool, but to destroy the client's JDBC connection to the pool. Any transaction on the connection is rolled back and the connection is returned to the connection pool. The client's JDBC connection context is no longer valid.

When a pool is enabled after it has been disabled with disableFreezingUsers(), the JDBC connection states for each in-use connection are exactly as they were when the connection pool was disabled; clients can continue JDBC operations exactly where they left off.

You can also use the disable_pool and enable_pool commands of the weblogic.Admin class to disable and enable a pool.

Shrinking a Connection Pool

  weblogic.jdbc.common.Pool.shrink()

A connection pool has a set of properties that define the initial and maximum number of connections in the pool (initialCapacity and maxCapacity), and the number of connections added to the pool when all connections are in use (capacityIncrement). When the pool reaches its maximum capacity, the maximum number of connections are opened, and they remain opened unless you shrink the pool.

You may want to drop some connections from the connection pool when a peak usage period has ended, freeing up resources on the WebLogic Server and DBMS.

Shutting Down a Connection Pool

  weblogic.jdbc.common.Pool.shutdownSoft()

  weblogic.jdbc.common.Pool.shutdownHard()

These methods destroy a connection pool. Connections are closed and removed from the pool and the pool dies when it has no remaining connections. Only the "system" user or users granted "admin" permission by an ACL associated with a connection pool can destroy the pool.

The shutdownSoft() method waits for connections to be returned to the pool before closing them.

The shutdownHard() method kills all connections immediately. Clients using connections from the pool get exceptions if they attempt to use a connection after shutdownHard() is called.

You can also use the destroy_pool command of the weblogic.Admin class to destroy a pool.

Resetting a Pool

  weblogic.jdbc.common.Pool.reset()

You can configure a connection pool to test its connections either periodically, or every time a connection is reserved or released. Allowing the WebLogic Server to automatically maintain the integrity of pool connections should prevent most DBMS connection problems. In addition, WebLogic provides methods you can call from an application to refresh all connections in the pool or a single connection you have reserved from the pool.

The weblogic.jdbc.common.Pool.reset() method closes and reopens all allocated connections in a connection pool. This may be necessary after the DBMS has been restarted, for example. Often when one connection in a connection pool has failed, all of the connections in the pool are bad.

Use any of the following methods to reset a connection pool:

- The Administration Console.

- The weblogic.Admin command (as a user with administrative privileges) to reset a connection pool. Here is the pattern:

  >     $ java weblogic.Admin WebLogicURL RESET_POOL poolName system passwd

  You might use this method from the command line on an infrequent basis. There are more efficient programmatic ways that are also discussed here.

- The reset() method from the weblogic.common.Pool interface in your client application.

  The last case requires the most work for you, but also gives you flexibility. To reset a pool using the reset() method:

  1. In a try block, test a connection from the connection pool with a SQL statement that is guaranteed to succeed under any circumstances so long as there is a working connection to the DBMS. An example is the SQL statement "select 1 from dual" which is guaranteed to succeed for an Oracle DBMS.

  2. Catch the SQLException.

  3. Call the reset() method in the catch block.

Using MultiPools

A MultiPool is a "pool of pools." MultiPools contain a configurable algorithm for determining the connection pool from which a connection is returned to an application: either high availability or connection pool load balancing.

MultiPools differ from connection pools in that all the connections in a particular connection pool are created identically with a single database, single user, and the same connection attributes. However, the connection pools within a MultiPool may be associated with different users or DBMSs.

Figure 4-1 MultiPool Architecture

Note that although a Multipool can return connections from multiple databases or with different users, WebLogic Server does not provide any means to integrate or handle the contents of disparate databases. Your application or DBMS environment must handle the synchronization or data integration so that your application will work transparently and successfully when it receives a connection from any of the underlying connection pools.

Choosing the MultiPool Algorithm

Before you set up a MultiPool, you need to determine the primary purpose of the MultiPool—high availability or load balancing. You can choose the algorithm that corresponds with your requirements.

High Availability

The High Availability algorithm provides an ordered list of connection pools. Normally, every connection request to this kind of MultiPool is served by the first pool in the list. If the first pool loses connectivity to the database, then a connection is sought sequentially from the next pool on the list.

Notes: You must set TestConnectionsOnReserve=true for the connection pools within the MultiPool so that the MultiPool can determine when to fail over to the next connection pool in the list.

If all connections in a connection pool are being used, a MultiPool with the High Availability algorithm will not attempt to provide a connection from the next pool in the list. This is by design so that you can set the capacity for a connection pool. MultiPool fail-over takes effect only if loss of database connectivity has occurred. To avoid this situation, you should increase the maximum number of connections in the connection pool.

Load Balancing

Connection requests to a load balancing MultiPool are served from any connection pool in the list. Pools are added without any attached ordering and are accessed using a round-robin scheme. When switching connections, the connection pool just after the last pool accessed is selected.

MultiPool Fail-Over Limitations and Requirements

WebLogic Server provides the High Availability algorithm for MultiPools so that if a connection pool fails (for example, if the database management system crashes), your system can continue to operate.

Connection pools rely on the TestConnectionsOnReserve feature to know when database connectivity is lost. Connections are not automatically tested before being reserved by an application. You must set TestConnectionsOnReserve=true for the connection pools within the MultiPool. After turning on this feature, WebLogic Server will test each connection before returning it to an application, which is crucial to the High Availability algorithm operation. With the High Availability algorithm, the MultiPool uses the results from testing connections on reserve to determine when to fail over to the next connection pool in the MultiPool. After a test failure, the connection pool attempts to recreate the connection. If that attempt fails, the MultiPool fails over to the next connection pool.

It is possible for a connection to fail after being reserved, in which case your application must handle the failure. WebLogic Server cannot provide fail-over for connections that fail while being used by an application. Any failure while using a connection requires that you restart the transaction and provide code to handle such a failure.

Guidelines to Setting Wait for Connection Times

Setting wait for connection times is a property of the connection attempt. If you are familiar with setting waiting time to pool connections, the wait for connection property applies to every connection tapped in a given connection attempt.

You can add any connection pool to a MultiPool. However, you optimize your resources depending on how you set the wait for connection time when you configure your connection pools.

Messages and Error Conditions

Users may request information regarding the connection pool from which the connection originated.

Exceptions

Exceptions are posted to the JDBC log under these circumstances:

- At boot time, when a connection pool is added to a MultiPool.

- Whenever there is a switch to a new connection pool within the MultiPool, either during load balancing or high availability.

Capacity Issues

In a high availability scenario, the fact that the first pool in the list is busy does not trigger an attempt to get a connection from the next pool in the list.

Configuring and Using DataSources

As with Connection Pools and MultiPools, you can create DataSource objects in the Administration Console or using the WebLogic Management API. DataSource objects can be defined with or without transaction services. You configure connection pools and MultiPools before you define the pool name attribute for a DataSource.

DataSource objects, along with the JNDI, provide access to connection pools for database connectivity. Each DataSource can refer to one connection pool or MultiPool. However, you can define multiple DataSources that use a single connection pool. This allows you to define both transaction and non-transaction-enabled DataSource objects that share the same database.

WebLogic Server supports two types of DataSource objects:

- DataSources (for local transactions only)

- TxDataSources (for distributed transactions)

If your application meets any of the following criteria, you should use a TxDataSource in WebLogic Server:

- Uses the Java Transaction API (JTA)

- Uses the WebLogic Server EJB container to manage transactions

- Includes multiple database updates during a single transaction.

For more information about when to use a TxDataSource and how to configure a TxDataSource, see JDBC Configuration Guidelines for Connection Pools, MultiPools, and DataSources.

If you want applications to use a DataSource to get a database connection from a connection pool (the preferred method), you should define the DataSource in the Administration Console before running your application. For instructions to create a DataSource, see the Administration Console Online Help. For instructions to create a TxDataSource, see the Administration Console Online Help.

Importing Packages to Access DataSource Objects

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

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

Obtaining a Client Connection Using a DataSource

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

>     Context ctx = null;
>       Hashtable ht = new Hashtable();
>       ht.put(Context.INITIAL_CONTEXT_FACTORY,
>              "weblogic.jndi.WLInitialContextFactory");
>       ht.put(Context.PROVIDER_URL,
>              "t3://hostname:port");

>       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:

>        stmt.close();
>        conn.close();
>      }
>       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 uses one of several available procedures for obtaining a JNDI context. For more information on JNDI, see Programming WebLogic JNDI.

Code Examples

See the DataSource code example in the samples/examples/jdbc/datasource directory of your WebLogic Server installation.

Copyright © 2001 BEA Systems, Inc. All rights reserved. Required browser: Netscape 4.0 or higher, or Microsoft Internet Explorer 4.0 or higher.