似乎每次我想执行db查询时,我都要编写以下内容:
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement(sql);
// ...set stmt params
rset = stmt.executeQuery();
while(rset.next()) {
// Do something interesting
}
} finally {
try { if (rset != null) rset.close(); } catch(SQLException e) { }
try { if (stmt != null) stmt.close(); } catch(SQLException e) { }
try { if (conn != null) conn.close(); } catch(SQLException e) { }
}
Run Code Online (Sandbox Code Playgroud)
这真的是最好的方法吗?有没有办法至少减少一些混乱?
编辑:作为一些评论指出的那样,这个代码不长不够.
Nic*_*olt 11
是的,使用Sping JDBC Template类(http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html).
或者,如果您不使用Spring复制他们在您自己的代码中使用的模板模式.
如果您已有DataSource,则可以使用Spring JdbcTemplate:
如果它看起来太沉重,你可以为'样板部件'实现一些实用程序类和方法.在这种情况下,研究JdbcTemplate的源代码应该会有所帮助.
| 归档时间: |
|
| 查看次数: |
2571 次 |
| 最近记录: |