11.2. Sharing Database Connections

When a connection to the database is established by a SQLJ program using the connect( ) or getConnection( ) methods, an underlying JDBC connection is created. Through that connection, communication between the program and the database takes place. You can extract this underlying JDBC connection from the SQLJ connection context and use it to access the database using JDBC statements. In this way, one connection is used for both SQLJ and JDBC statements. Similarly, you can also create—or re-use—a JDBC connection and use it to create a SQLJ connection context, which may then be used by SQLJ statements to access the database.

Shared database connections also share the same database session and transaction.

I discuss sharing a SQLJ connection with JDBC first, and then discuss sharing a JDBC connection with SQLJ.

11.2.1. Sharing a SQLJ Connection with JDBC

To share a database connection established by a SQLJ connection context with JDBC, you must perform the following steps:

  1. Call the getConnection( ) method in the sqlj.runtime.ref.DefaultContext class using a SQLJ connection context; this method returns the underlying JDBC connection for the connection context.

  2. Assign the JDBC connection returned by getConnection( ) to a JDBC connection object.

The following example creates a SQLJ connection context named sqlj_conn_context that accesses the ...

Get Java Programming with Oracle SQLJ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.