Java – general helper for closing JDBC objects

It is strongly recommended to close JDBC objects (connections, statements, result sets) when using them However, this generates a lot of code:

Connection conn = null;
Statement stm = null;
ResultSet res = null;
try {
  // Obtain connection / statement,get results,whatever...
} catch (sqlException e) {
  // ...
} finally {
  if (res != null) { try { res.close(); } catch (sqlException ignore) {}}
  if (stm != null) { try { stm.close(); } catch (sqlException ignore) {}}
  if (conn != null) { try { conn.close(); } catch (sqlException ignore) {}}
}

Now I want to reduce the amount of code that closes objects by implementing an auxiliary function It takes objects as arguments and tries to call each object's close () method using reflection (if the object does have such a method)

public void close(Object... objects) {
  for (Object object : objects) {
    for (Method method : object.getClass().getmethods()) {
      if (method.getName().equals("close")) {
        try {
          method.invoke(object);
        } catch (Exception e) {
          e.printStackTrace();
        }
        break; // break on the methods,go for the next object
      }
    }
  }
}

Finally blocks can be simplified to:

} finally {
  close(res,stm,conn);
}

Is this a good thing? If not, why? Is there a better way?

Solution

Personally, I won't use reflection in this case, when there are many good ways to do this without it Here are a few things you can do

>Using spring Spring has a jdbctemplate object, which helps to reduce the redundancy of JDBC coding The template code is hidden in the implementation of the jdbctemplate, so you are free to perform important operations on your application. > Using java 7 Java 7 provides a new language structure that makes it easier to close objects that implement the autoclosable interface. > Create your own library to handle template code If spring demands too much of you, you can easily complete all closures in a base class from which the JDBC interaction class can be extended You will have to write once, but it can be out of sight in most cases

The Java 7 approach looks like this:

try (
    Connection conn = getConnectionSomehow();
    Statement statement = getStatementFromConnSomehow(conn);
) {
    //use connection
    //use statement
} catch(SomeException ex) {
    //do something with exception
}//hey,check it out,conn and statement will be closed automatically! :)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>