Clear Duplicate Settings and Clear Java Code (JDBC)

I have too many methods that repeatedly do something like

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) {}
}

This setting / disabling / cleaning of statements and result sets is repeated and hides interesting pieces of code.

Is there any template or idiom for handling this (without introducing any external frameworks)?

+5
source share
5 answers

You can create a method that receives an SQL query and an object to process ResultSet. eg:

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) {}
  }
}

c ResultSetHandleris the interface:

public interface ResultSetHandler {
  void handle(ResultSet rs) throws SQLException;
}

and you can create an object of an anonymous class that implements this interface, so it won’t clutter up too much.

+4
source

SimpleJDBCTemplate Spring Framework. , .

, , .

+10

Execute Around.

, " " "?.

( ASCII: " " )

+4

Java-, iBatis Hibernate. . iBatis, SQL XML, 25% JDBC. iBatis.

+1

, JDBC:

Statement statement = connection.createStatement();
try {
    ResultSet results = statement.executeQuery(...);
    try {
        while (results.next()) {
            //handle rows
        }
    } finally {
        results.close();
    }
} finally {
    statement.close();
}

Nested blocks tryautomatically ensure that both methods resultsand statementwill have their own methods close(), without recourse to the operators try/ catchin your block finally. In addition, starting with blocks tryimmediately after acquiring your objects, you do not need to worry about checking values null(unless, of course, connection.createStatement()or statement.executeQuery(...) does not return null- In in this case you have more problems).

0
source

All Articles