public final class JDBCTools
extends java.lang.Object
closeQuietly(..) methods allow short and easy clean-up code
to be used in the finally-block. They swallow SQLExceptions and check
for null, so you don't have to do it. Don't use them as the only
mechanism for closing result sets, statements etc.! (See the suggested
pattern below.)close(..) methods allow to close a ResultSet, a
(Prepared)Statement and a Connection (with variations for different
combinations) in a single line. There are versions for single objects that
currently provide no other advantage than consistency.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
con = getDataSource().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(<query>);
// read from the result set
rs = JDBCTools.close(rs);
stmt = JDBCTools.close(stmt);
con = JDBCTools.close(con);
// now all three variables are null and it won't be tried to close them
// again in the finally block
}
catch (SQLException ex) // the catch part is optional, depending on which exceptions your method may throw
{
throw new DataSourceException(ex);
}
finally
{
JDBCTools.closeQuietly(con, stmt, rs);
}
Note, that the resources are also closed in the try-block and not just in the
finally-block. The first ensures that potential exceptions during the regular
releasing of resources are not swallowed, while the latter ensures that even
after runtime exceptions the resources are properly released. This differs
from a common so called "best practice" where everything is closed
exclusively in the finally-block.
Exceptions in the finally-block are swallowed since they would override exceptions from the try- or catch-blocks.
This pattern may of course be extended if more variables for (prepared) statements and/or result sets are needed.
To use transactions only auto-commit has to be turned off. Everything else stays the same:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
con = getDataSource().getConnection();
con.setAutoCommit(false);
stmt = con.createStatement();
rs = stmt.executeQuery(<query>);
// read from the result set
rs = JDBCTools.close(rs);
stmt = JDBCTools.close(stmt);
con = JDBCTools.close(con); // this will attempt a commit before closing the connection
// now all three variables are null and it won't be tried to close them
// again or to rollback in the finally block
}
catch (SQLException ex) // the catch part is optional, depending on which exceptions your method may throw
{
throw new DataSourceException(ex);
}
finally
{
JDBCTools.closeQuietly(con, stmt, rs); // this will also attempt a rollback on the connection
}
TODO: example with transaction(s) where connection is created elsewhere and auto commit state is not known in advance
| Modifier and Type | Field and Description |
|---|---|
static long |
MAX_TIMESTAMP
timestamp for 9999-12-31 23:59:59 (UTC)
|
static long |
MIN_TIMESTAMP
timestamp for 0001-01-01 00:00:00 (UTC)
|
| Modifier and Type | Method and Description |
|---|---|
static <C extends java.sql.Connection> |
close(C con)
Closes the given connection and returns
null after attempting a
commit (only if auto-commit is turned off). |
static <R extends java.sql.ResultSet> |
close(R rs)
Closes the given result set and returns
null. |
static <S extends java.sql.Statement> |
close(S stmt)
Closes the given statement and returns
null. |
static void |
closeQuietly(java.sql.Connection con)
Attempts a rollback (if auto-commit is off) and then (in either case)
closes the given connection, ignoring
null values and swallowing
SQLExceptions. |
static void |
closeQuietly(java.sql.Connection con,
java.sql.Statement stmt)
Closes the given connection and statement, ignoring
null values and
swallowing SQLExceptions. |
static void |
closeQuietly(java.sql.Connection con,
java.sql.Statement stmt,
java.sql.ResultSet rs)
Closes the given result set, statement and connection ignoring
null
values and swallowing SQLExceptions. |
static void |
closeQuietly(java.sql.ResultSet rs)
Closes the given result set, ignoring
null values and swallowing
SQLExceptions. |
static void |
closeQuietly(java.sql.Statement... stmts)
Closes the given statements, ignoring
null values and swallowing
SQLExceptions. |
static void |
closeQuietly(java.sql.Statement stmt)
Closes the given statement, ignoring
null values and swallowing
SQLExceptions. |
static void |
closeQuietly(java.sql.Statement stmt,
java.sql.ResultSet rs)
Closes the given statement and result set, ignoring
null values and
swallowing SQLExceptions. |
static <C extends java.sql.Connection> |
commit(C con)
Performs a commit and returns
null. |
static java.util.Calendar |
createUTCCalendar()
Returns a new
Calendar with UTC as its time zone. |
static java.sql.SQLException |
generalise(java.sql.SQLException ex,
java.util.logging.Logger generalLogger)
Converts every JDBC-driver specific subclass of SQLException to a general
SQLException.
|
static java.sql.SQLClientInfoException |
generaliseSQLClientInfoException(java.sql.SQLClientInfoException ex,
java.util.logging.Logger generalLogger)
Converts every JDBC-driver specific subclass of SQLException to a general
SQLException.
|
static <C extends java.sql.Connection> |
restoreAutoCommit(C con,
java.lang.Boolean previousAutoCommitState)
If auto-commit was previously on, a commit is performed and auto-commit is
turned on again.
|
static <C extends java.sql.Connection> |
restoreAutoCommit(C con,
java.sql.Savepoint sp,
java.lang.Boolean previousAutoCommitState)
If auto-commit was previously on, a commit is performed and auto-commit is
turned on again.
|
static void |
rollbackQuietly(java.sql.Connection con)
Will try to rollback the current transaction of the given connection, but
only if auto commit is turned off.
|
static void |
rollbackQuietly(java.sql.Connection con,
java.lang.Boolean previousAutoCommitState)
Will try to rollback the current transaction of the given connection, but
only if auto commit is turned off.
|
static void |
rollbackQuietly(java.sql.Connection con,
java.sql.Savepoint sp)
Will try to rollback the current transaction of the given connection to the
given savepoint, but only if auto commit is turned off.
|
static void |
rollbackQuietly(java.sql.Connection con,
java.sql.Savepoint sp,
java.lang.Boolean previousAutoCommitState)
Will try to rollback the current transaction of the given connection to the
given savepoint, but only if auto commit is turned off.
|
static int |
setMaximumIsolationLevel(java.sql.Connection con,
int isoLevel)
Sets the isolation level of the designated connection to at most the
designated one.
|
static int |
setMinimumIsolationLevel(java.sql.Connection con,
int isoLevel)
Sets the isolation level of the designated connection to at least the
designated one.
|
static java.lang.String |
toString(java.sql.Date d)
Formats an SQL date to JDBC date escape format.
|
static java.lang.String |
toString(java.sql.Time t)
Formats an SQL time to JDBC time escape format.
|
static java.lang.String |
toString(java.sql.Timestamp ts)
Formats an SQL timestamp to JDBC timestamp escape format.
|
static java.sql.Date |
trim(java.sql.Date d)
Returns a new date that is guaranteed to be after
MIN_TIMESTAMP
and before MAX_TIMESTAMP, if the given date is not within these
bounds. |
static java.sql.Timestamp |
trim(java.sql.Timestamp ts)
Returns a new timestamp that is guaranteed to be after
MIN_TIMESTAMP and before MAX_TIMESTAMP, if the given
timestamp is not within these bounds. |
static java.lang.Boolean |
turnOffAutoCommit(java.sql.Connection con)
Turns off auto-commit of the given connection and returns the previous
state.
|
public static final long MIN_TIMESTAMP
public static final long MAX_TIMESTAMP
public static java.lang.Boolean turnOffAutoCommit(java.sql.Connection con)
throws java.sql.SQLException
con - the connection on which to set the auto-commit statejava.sql.SQLException - if a database access error occurspublic static <R extends java.sql.ResultSet> R close(R rs)
throws java.sql.SQLException
null. The intended usage
pattern is as follows:
rs = JDBCTools.close(rs)This ensures that the variable is null and the object can't (accidentally) be used any longer. Also, the finally block does not try to close the object again, since its reference is null now.
rs - the result set to be closedjava.sql.SQLException - if a database access error occurspublic static <S extends java.sql.Statement> S close(S stmt)
throws java.sql.SQLException
null. The intended usage
pattern is as follows:
stmt = JDBCTools.close(stmt)This ensures that the variable is null and the object can't (accidentally) be used any longer. Also, the finally block does not try to close the object again, since its reference is null now.
S - to support all subtypes of Statementstmt - the statement to be closedjava.sql.SQLException - if a database access error occurspublic static <C extends java.sql.Connection> C close(C con)
throws java.sql.SQLException
null after attempting a
commit (only if auto-commit is turned off). The intended usage pattern is
as follows:
con = JDBCTools.close(con);This ensures that the variable is null and the object can't (accidentally) be used any longer. Also, the finally block does not try to close the object again, since its reference is null now.
C - to support all subtypes of Connectioncon - the connection set to be closedjava.sql.SQLException - if a database access error occurspublic static <C extends java.sql.Connection> C commit(C con)
throws java.sql.SQLException
null. Intended for cases where the
connection is provided from outside (e.g. given as method parameter) and
should therefore not be closed.C - to support all subtypes of Connectioncon - the connection on which to perform the commitjava.sql.SQLException - if a database access error occurspublic static <C extends java.sql.Connection> C restoreAutoCommit(C con,
java.lang.Boolean previousAutoCommitState)
throws java.sql.SQLException
C - to support all subtypes of Connectioncon - the connection on which to perform the commitpreviousAutoCommitState - the previous state of auto-commit or
nulljava.sql.SQLException - if a database access error occurspublic static <C extends java.sql.Connection> C restoreAutoCommit(C con,
java.sql.Savepoint sp,
java.lang.Boolean previousAutoCommitState)
throws java.sql.SQLException
C - to support all subtypes of Connectioncon - the connection on which to perform the commitsp - the savepoint to releasepreviousAutoCommitState - the previous state of auto-commit or nulljava.sql.SQLException - if a database access error occurspublic static void closeQuietly(java.sql.Connection con,
java.sql.Statement stmt,
java.sql.ResultSet rs)
null
values and swallowing SQLExceptions. Before closing the
connection a rollback is attempted. This method is only intended to be
used in a finally-block.con - the connection to be silently closed (if not null)stmt - the statement to be silently closed (if not null)rs - the result set to be silently closed (if not null)public static void closeQuietly(java.sql.Connection con,
java.sql.Statement stmt)
null values and
swallowing SQLExceptions. Before closing the connection a
rollback is attempted. This method is only intended to be used in a
finally-block.con - the connection to be silently closed (if not null)stmt - the statement to be silently closed (if not null)public static void closeQuietly(java.sql.Statement stmt,
java.sql.ResultSet rs)
null values and
swallowing SQLExceptions. This method is only intended to be used
in a finally-block.stmt - the statement to be silently closed (if not null)rs - the result set to be silently closed (if not null)public static void closeQuietly(java.sql.Connection con)
null values and swallowing
SQLExceptions. This method is only intended to be used in a
finally-block.con - the connection to be silently closed (if not null)public static void closeQuietly(java.sql.Statement... stmts)
null values and swallowing
SQLExceptions. This method is only intended to be used in a
finally-block.stmts - the statements to be silently closedpublic static void closeQuietly(java.sql.Statement stmt)
null values and swallowing
SQLExceptions. This method is only intended to be used in a
finally-block.stmt - the statement to be silently closed (if not null)public static void closeQuietly(java.sql.ResultSet rs)
null values and swallowing
SQLExceptions. This method is only intended to be used in a
finally-block.rs - the result set to be silently closed (if not null)public static void rollbackQuietly(java.sql.Connection con)
con - the connection to rollbackpublic static void rollbackQuietly(java.sql.Connection con,
java.lang.Boolean previousAutoCommitState)
con - the connection to rollbackpreviousAutoCommitState - the previous state of the auto-commit flag
that will be restored (if possible); null to leave the
flag as ispublic static void rollbackQuietly(java.sql.Connection con,
java.sql.Savepoint sp)
con - the connection to rollbacksp - the savepoint to roll back topublic static void rollbackQuietly(java.sql.Connection con,
java.sql.Savepoint sp,
java.lang.Boolean previousAutoCommitState)
con - the connection to rollbacksp - the savepoint to roll back topreviousAutoCommitState - the previous state of the auto-commit flag
that will be restored (if possible); null to leave the
flag as ispublic static java.lang.String toString(java.sql.Date d)
Date.toString() this method does not convert to the default
timezone, but leaves the date as is.d - the date to be formattedjava.lang.IllegalArgumentException - if the date is before
MIN_TIMESTAMP or after MAX_TIMESTAMPpublic static java.lang.String toString(java.sql.Time t)
Time.toString() this method does not convert to the default
timezone, but leaves the time as is.t - the time to be formattedpublic static java.lang.String toString(java.sql.Timestamp ts)
Timestamp.toString() this method does not convert to the default
timezone, but leaves the timestamp as is.ts - the timestamp to be formattedjava.lang.IllegalArgumentException - if the timestamp is before
MIN_TIMESTAMP or after MAX_TIMESTAMPpublic static java.sql.Date trim(java.sql.Date d)
MIN_TIMESTAMP
and before MAX_TIMESTAMP, if the given date is not within these
bounds.d - public static java.sql.Timestamp trim(java.sql.Timestamp ts)
MIN_TIMESTAMP and before MAX_TIMESTAMP, if the given
timestamp is not within these bounds.ts - public static java.util.Calendar createUTCCalendar()
Calendar with UTC as its time zone.Calendar with UTC as its time zonepublic static java.sql.SQLException generalise(java.sql.SQLException ex,
java.util.logging.Logger generalLogger)
next exceptions.ex - any subclass of SQLExceptiongeneralLogger - the logger used to log generalised exceptions as
Level.FINE; null to not log themSQLException or any passed-through subclass from
the packages java.sql and javax.sqlpublic static java.sql.SQLClientInfoException generaliseSQLClientInfoException(java.sql.SQLClientInfoException ex,
java.util.logging.Logger generalLogger)
next exceptions.ex - any subclass of SQLExceptiongeneralLogger - the logger used to log generalised exceptions as
Level.FINE; null to not log themSQLException or any passed-through subclass from
the packages java.sql and javax.sqlpublic static int setMaximumIsolationLevel(java.sql.Connection con,
int isoLevel)
throws java.sql.SQLException
con - The connection of which to set the isolation level.isoLevel - The maximum isolation level which to have with the
designated connection.java.sql.SQLException - If there are problems setting the isolation level, an
SQLException will be thrown.public static int setMinimumIsolationLevel(java.sql.Connection con,
int isoLevel)
throws java.sql.SQLException
con - The connection of which to set the isolation level.isoLevel - The minimum isolation level which to have with the
designated connection.java.sql.SQLException - If there are problems setting the isolation level, an
SQLException will be thrown.