从db代码中删除样板

its*_*dok 7 java jdbc

似乎每次我想执行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复制他们在您自己的代码中使用的模板模式.


Csa*_*a_H 8

如果您已有DataSource,则可以使用Spring JdbcTemplate:

  • 大大减少了样板代码
  • 有一个很好的sql异常层次结构来处理特定运行时异常的常见数据库问题
  • (稍后使用Spring进一步使用)使用声明式事务管理

如果它看起来太沉重,你可以为'样板部件'实现一些实用程序类和方法.在这种情况下,研究JdbcTemplate的源代码应该会有所帮助.


Tim*_*m R 6

DbUtils是一个非常有用的框架,我已经将它用于Spring和Hibernate过度杀伤的小型项目.它也能够做一些对象映射.