I would like to close my connection after fulfilling a DB query. The thing is I am using prepared statement since they are pre-compiled so more secure. I want to close the DB connection so it can be reused later for another query.
The documentation says the following:
/**
* Create a statement in this connection. Allows implementations to use
* PreparedStatements. The JdbcTemplate will close the created statement.
* @param con the connection used to create statement
* @return a prepared statement
* @throws SQLException there is no need to catch SQLExceptions
* that may be thrown in the implementation of this method.
* The JdbcTemplate class will handle them.
*/
PreparedStatement createPreparedStatement(Connection con) throws SQLException;
I got into a situation where no connection was available in the pool.
I have the following but it throws an exception saying that no operations is allowed after statement closed.
private IRespondent InsertRespondentToken(IRespondent respondent) {
try{
final String insertRespondent = "insert into respondents_token (SynchroID,TerminalID,QuestionnaireID,ProjectID,Token) values (?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
(Connection con) -> {
try{
PreparedStatement pst = con.prepareStatement(insertRespondent, new String[] {"ID"});
pst.setInt(1, respondent.getSynchroId());
pst.setInt(2, respondent.getTerminalId());
pst.setInt(3, respondent.getQuestionnaireId());
pst.setInt(4,respondent.getProjectId());
respondent.setToken(GenerateUniqueId.getIdentifier());
pst.setString(5,respondent.getToken());
return pst;
}
catch (SQLException e)
{
log.error("Prepared statement failed! Read the stack!",e);
}
finally {
con.close(); // IS thsi right. Or there is another way of doing it.
}
return null;
}
,keyHolder);
}catch(NullPointerException ex){
log.error("Error during end element parsing.", ex);
if (respondent.getId() != -1)
deleteRespondent(respondent.getId());
return null;
}
return respondent;
}