At a minimum, you should switch to PreparedStatement instead of simple expressions. The reason for this is that the JDBC driver in most cases sends an instruction to the database at creation, so it can be precompiled. Then you can associate your parameters with the instruction and execute. In addition to the benefits of precompiling performance, you also get a little protection against SQL injection attacks, since the way you configure parameters is more strongly typed. There is a good description of trained operators on the Oracle Web site.
If you use Spring (or want to take a jump to add it to your system), you can take a look at the JdbcTemplate and JdbcDaoSupport (both highlighted here ). The main advantage is that it takes care of the connection clearing code for you (so you donβt have to worry about missing a close call).
Similarly, if you add Spring to your project, you can use it to configure transactions (via annotations or from the Spring context file). This will allow you to take transaction management out of the actual implementation and make the code in your Dao a little cleaner.
As for your commit / close processing: you have to transfer your transactional statements from your finally blocks and to the main execution path. You should keep your closed statements in a finally block, although since you want them to happen, they happen no matter what.
An example of how your update code will look with PreparedStatements is as follows:
public void updateMethod() { Connection con = null; PreparedStatement stmt = null; int updateCount = null; try { con = BoneCPConnection.getConnectionPool().getConnection(); stmt = con.prepareStatement("update example set id = ?"); stmt.setInt(1,1); updateCount = stmt.executeUpdate(query); con.commit(); } catch (Exception e) { if(con != null){ con.rollback(); } } finally { try { if(stmt != null){ stmt.close(); } if(con != null){ con.close(); } } catch (Exception e) { con = null; } } }
If you used Spring JdbcDaoSuport, it would look like this:
public class YourDao extends JdbcDaoSupport{ public void updateMethod(){ String sql = "update example set id = ?"; getJdbcTemplate().update(sql, new Object[] { new Integer(1)}); } }
source share