For insert record in database with JDBC, there are two approaches :
Nested try.. finally : In this approach, nested try with finally use for close prepare statement and connection
public void performInsert(String insertSQL) { try { Connection connection = dataSource.getConnection(); try { PreparedStatement insertStmt = connection .prepareStatement(insertSQL); try { // bind value to prepare statements insertStmt.executeUpdate(); } finally { insertStmt.close(); } } finally { connection.close(); } } catch (SQLException e) { // TODO: handle exception } }
single try with if condition in finally block : In this approach single try use and in finally block use if condition for close statement and connection:
public void performInsertIF(String insertSQL) { Connection connection = null; PreparedStatement insertStmt = null; try { connection = dataSource.getConnection(); insertStmt = connection.prepareStatement(insertSQL); // bind value to prepare statements insertStmt.executeUpdate(); }catch (SQLException e) { // TODO: handle exception } finally { if( insertStmt != null) { try { insertStmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if( connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Both above approach is working fine, but which approach is better to use and why ?