我目前正在创建许多使用连接池访问数据库的类。所以我得到了一个连接,创建了一个语句并得到了结果集。(我不能使用Java1.7和奇妙的自动资源管理)在完成我的方法时,我必须用一个最终块来完成:
if (rs != null) {
try {
rs.close();
} catch (SQLException sqle) {
logger.error("Couldn't close result set", sqle);
}
}
if (st != null) {
try {
st.close();
} catch (SQLException sqle) {
logger.error("Couldn't close statement", sqle);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException sqle) {
logger.error("Couldn't close connection", sqle);
}
}我已经看到了XX类的噩梦,每个类都有4/5的方法。
创建一个助手类,为每种对象类型提供一个特殊的关闭方法,这样做是否是一个好做法:
public static void closeResource(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException sqle) {
logger.error("Couldn't close connection", sqle);
}
}然后用xx.close(connection);xx.close(statement);xx.close(rs);做我平常的xx.close(connection);xx.close(statement);xx.close(rs);
或者在同样的想法中(我知道在这一点上我会让一些人震惊,因为我自己也会觉得有点烦躁),有一个像public static void closeResources(Object... obj) {}这样的方法,有一个糟糕的instanceof列表?
或者根据你的经验,在任何地方编写代码都更好?
发布于 2012-02-29 16:30:38
使用Apache:http://commons.apache.org/dbutils/apidocs/org/apache/commons/dbutils/DbUtils.html
DbUtils.closeQuietly()可能是您所需要的
发布于 2012-02-29 16:28:09
使用超载。
private void close(ResultSet rSet) throws SQLException {
if (rSet != null) {
rSet.close();
}
}
private void close(Statement statement) throws SQLException {
if (statement != null) {
statement.close();
}
}
private void close(Connection conn) throws SQLException {
if (conn != null) {
conn.close();
}
}现在的使用将更加清洁:
try {
// do db stuff
} catch (Exception e) {
logger.error("log it", e);
} finally {
close(rs);
close(cs);
close(conn);
}发布于 2012-02-29 16:54:29
再举一个例子。适用于简单的小项目。
Object doRequest() throws SQLException {
PreparedStatement ps = ... // initialize statement
try {
ResultSet rs = ps.executeQuery();
try {
// use ResultSet
return someResult;
} finally {
rs.close();
}
} finally {
ps.close();
}
}虽然它不是一个完全的解决方案(许多嵌套的try-finally都很难读),但有几个优点:
close().是否为null
https://stackoverflow.com/questions/9502851
复制相似问题