使用父函数处理连接池中所有杂乱的catch / finally内容有什么问题吗?
public Connection getConnection() {
try {
return this.dataSource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ResultSet executeQuery(Connection connection, PreparedStatement stmt) {
try {
return stmt.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
答案 0 :(得分:3)
没有问题,除了你正在吃异常并且不抛弃它们。抛出异常是一个更好的主意,允许调用方法采取适当的行动。
注意:如果您可以转到Java 7并使用try with resource,那么您将节省大量此类混乱。请在此处详细了解:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
答案 1 :(得分:2)
它没有任何问题,除了你应该制作那些方法static
,所以它们是(无状态的)实用方法。
答案 2 :(得分:0)
如果您使用try-with-resources模式并且专注于最小化资源范围,那么您将获得更清晰的代码。特别是,您有问题地将资源(连接和语句)与关闭行为分开打开。通过拆分,您可以轻松犯错误或创建低效的代码。例如,也许您不应该在执行查询后关闭连接。
相反,您通常应该在同一个地方打开和关闭资源,并且您可以在任何地方传递您信任的这些资源(创建一个不变量),它们将保持打开状态。这样可以清楚地区分使用资源行为中的获取资源行为,并允许您明确限制这些资源的开放范围。
比较你的代码:
Connection conn = getConnection();
PreparedStatement ps = ...; // construct PreparedStatement
ResultSet rs = executeQuery(conn, ps);
// use ResultSet
/* now secretly your Connection and PreparedStatement are closed (even if you wanted
to use them again) though your result set is still open and needs to be closed.
Admittedly it's concise, but what's actually going on is very unclear. */
到我的代码:
public static void main(String[] args) {
try(Connection conn = this.dataSource.getConnection()) {
// All calls in this block, and only calls in this block, can use the connection
buildObjectWithDBData(conn); // method does exactly what the name implies
// do more calls against our connection as needed
}
}
public static void buildObjectWithDBData(Connection conn) {
try(PreparedStatement ps = /* generate prepared statement */;
ResultSet rs = ps.executeQuery()) {
// do work with result set, populate the data we need
}
// at this point we know the connection is alive in a clean, stable state,
// the resources opened here are closed, and we've done the work we need
}
我会批准,我的更加冗长。但它很多更清楚它正在做什么,并且在流程的每一步我们都明确地将对象和资源的范围限制为尽可能少,而不是依赖于任意方法调用的副作用秘密关闭物品并将它们留在范围内,但无法使用。