6.5. Access to SQL Connections
Prev | Chapter 6. Standard Features | Next

## 6.5. Access to SQL Connections

Kodo JDO provides two mechanisms for obtaining a `java.sql.Connection` object. This can be useful when direct access to the underlying data store is required.

The following code obtains the connection that is currently in use by a particular `PersistenceManager`. If there is no connection open to the data store for the given thread, then a new one is created and returned. If a data store transaction is in progress, then the connection returned will be transactionally consistent. See the Javadoc for `com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager` for more details.

Example 6.1. Obtaining a java.sql.Connection object from the PersistenceManager

    PersistenceManagerFactory factory = ...; // obtain a PersistenceManagerFactory
    PersistenceManagerImpl pm =
      (PersistenceManagerImpl) factory.getPersistenceManager ();
    JDBCStoreManager storeManager = (JDBCStoreManager) pm.getStoreManager ();
    Connection conn = storeManager.getConnection ();

    // do stuff

    storeManager.releaseConnection (conn);

The connection returned can safely be released regardless of the current transactional state, and regardless of whether or not the PersistenceManager is being closed. Releasing the connection does not close the connection unless appropriate.

Additionally, a connection that is in no way linked to the current PersistenceManager can be obtained using Kodo JDO:

    PersistenceManagerFactory factory = ...;
    DataSource dataSource = (DataSource) factory.getConnectionFactory ();
    Connection conn = dataSource.getConnection ();

Note that for this example, it is up to you to do all cleaning up. Additionally, you may need to enter a username and password when obtaining a connection from the DataSource, depending on how you created the `PersistenceManagerFactory`.

Prev | Up | Next
6.4. Custom Proxies | Home | 6.6. PersistenceManagerImpl.evictAll() API extensions