日期:2014-05-16  浏览次数:20388 次

使用模板方法模式简化JDBC操作
在使用JDBC时,会重复的写很多重复的代码,例如

   
Java代码 
1.              Connection conn = null;  
2.PreparedStatement ps = null;  
3.ResultSet rs = null;  
4.              String sql="insert into t_user(username,brithday) values(?,?)";  
5.try {  
6.    conn = JdbcUtils.getConnection();  
7.    ps = conn.prepareStatement(sql);  
8.      
9. 
10.} catch (SQLException e) {  
11.    throw new DaoException(e.getMessage(), e);  
12.} finally {  
13.    JdbcUtils.free(rs, ps, conn);  
14.}  
15.   
                Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
                String sql="insert into t_user(username,brithday) values(?,?)";
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);


} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
   

这部分代码在数据库操作方法中都会有。因此我们可以把这部分不变的内容提取出来,作为一个公用的方法。

例如,我们的增,删,改操作可以这样写

Java代码 
1./** 
2.     * 增,删,改方法 
3.     * @param sql 
4.     * @param args sql参数 
5.     * @return 
6.     */ 
7.    public int update(String sql, Object[] args) {  
8.        Connection conn = null;  
9.        PreparedStatement ps = null;  
10.        ResultSet rs = null;  
11.        try {  
12.            conn = JdbcUtils.getConnection();  
13.            ps = conn.prepareStatement(sql);  
14.            for (int i = 0; i < args.length; i++)  
15.                ps.setObject(i + 1, args[i]);  
16.            return ps.executeUpdate();  
17.        } catch (SQLException e) {  
18.            throw new DaoException(e.getMessage(), e);  
19.        } finally {  
20.            JdbcUtils.free(rs, ps, conn);  
21.        }  
22.    } 
/**
* 增,删,改方法
* @param sql
* @param args sql参数
* @return
*/
public int update(String sql, Object[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1,