I have client's methods that processes a large SQL query. I wouldn't like to do that through getting whole query result to memory, but process it in batches. It entails with exposing JDBC API to client's code. I think that this code could be refactored much better.
//client's method
m_jdbcManager = JdbcManagerUtil.getInstance();
m_tupleManager = DbTupleManager.getInstance();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = m_jdbcManager.getConnection();
connection.setAutoCommit(false);
statement = connection
.prepareStatement(Statements.SELECT_RIGHT_TUPLES);
statement.setInt(1, id);
statement.setFetchSize(JdbcManagerUtil.FETCH_SIZE);
resultSet = statement.executeQuery();
while (resultSet.next()) {
Tuple tuple = (Tuple) m_tupleManager
.readObject(resultSet);
//process tuple, invokes methods from client class
}
connection.setAutoCommit(true);
JdbcManagerUtil.closeEverything(connection, statement, resultSet);
} catch (<exceptions>) {
}
I tried to expose method that returns ResultSet
, but after processing, there must be released resources Connection
, PreparedStatement
and ResultSet
.
JDBC 4 and PostreSQL database.
setAutoCommit(true)
andcloseEverything
needs to be in afinally
block. Outherwise, you may leak resources or break down codes that rely onautoCommit
beingtrue
. – abuzittin gillifirca Jan 17 '14 at 15:23