从db代码中删除样板 [英] Remove boilerplate from db code
本文介绍了从db代码中删除样板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
似乎每次我想执行数据库查询时,我都要编写以下内容:
It seems that every time I want to perform a db query, I have to write the following:
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) { }
}
这真的是最好的办法吗这个?有没有办法至少减少一些混乱?
Is this really the best way to do this? Is there a way to at least reduce some of the clutter?
编辑:正如一些评论指出的那样,这段代码不够长足够
。Edited: as some of the comments pointed out, this code wasn't long enough.
推荐答案
如果您已有数据源,则可以使用 Spring JdbcTemplate :
If you already have a DataSource you can use Spring JdbcTemplate for:
- 大大减少样板代码
- 有一个好的 sql异常层次结构,用于处理特定运行时异常的常见数据库问题
- (稍后进一步Spring使用)使用声明式事务管理
- greatly reduced boilerplate code
- have a good sql exception hierarchy to handle common database problems with specific runtime exceptions
- (later with further Spring usage) use declarative transaction management
如果它看起来太重,你可以为'样板实现一些实用程序类和方法部分'。在这种情况下,研究JdbcTemplate的源代码应该会有所帮助。
If it seems too heavy for the moment you could implement some utility classes and methods for the 'boilerplate part'. Studying the source of JdbcTemplate should help in this case.
这篇关于从db代码中删除样板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文