清理重复设置和清理Java(JDBC)代码

nos*_*nos 5 java refactoring jdbc

我有太多方法可以反复做类似的事情

Statement stmt = null;
ResultSet rstmt = null;
try {
    stmt = conn.createStatement();
    rstmt = stmt.executeQuery(...);
    while (rstmt.next()) {
        //handle rows
    }


} catch (SQLException e) {
    //handle errors

} finally {
    try {rstmt.close();} catch (SQLException ex) {}
    try {stmt.close();} catch (SQLException ex) {}
}
Run Code Online (Sandbox Code Playgroud)

语句和结果集的这种设置/拆除/清理是重复的,并隐藏有趣的代码片段.

是否有任何模式或习惯用于处理此问题(不引入任何外部框架)?

Mar*_*ark 10

在Spring Framework中查看SimpleJDBCTemplate.这完全符合你的要求.

如果您不想引入外部框架,那么只需使用它来实现您自己的灵感.


cd1*_*cd1 4

您可以创建一个接收 SQL 查询的方法和一个处理ResultSet. 例如:

private void executeSql(String sql, ResultSetHandler handler) {
  Statement stmt = null;
  ResultSet rstmt = null;
  try {
    stmt = conn.createStatement();
    rstmt = stmt.executeQuery(sql);
    while (rstmt.next()) {
      handler.handle(rstmt);
    }
  }
  catch (SQLException e) {
    //handle errors
  }
  finally {
    try {rstmt.close();} catch (SQLException ex) {}
    try {stmt.close();} catch (SQLException ex) {}
  }
}
Run Code Online (Sandbox Code Playgroud)

作为ResultSetHandler一个接口:

public interface ResultSetHandler {
  void handle(ResultSet rs) throws SQLException;
}
Run Code Online (Sandbox Code Playgroud)

并且您可以创建实现该接口的匿名类的对象,因此它不会太混乱。