java数据访问:这是java数据访问代码的良好风格,还是它太多了?
这是java数据访问代码的良好风格,还是尝试最后太多了?
public List<Item> getItems() throws ItemException {
ArrayList<Item> items = new ArrayList<Item>();
try {
Connection con = ds.getConnection();
try {
PreparedStatement pStmt = con.prepareStatement("SELECT ....");
try {
ResultSet rs = pStmt.executeQuery();
try {
while (rs.next()) {
Item item = new Item();
item.setItemNo(rs.getString("item_id"));
// ...
items.add(item);
}
} finally {
rs.close();
}
} finally {
pStmt.close();
}
} finally {
con.close();
}
} catch (SQLException e) {
throw new ItemException(e);
}
return items;
}
Is this good style of java data access code, or is it too much try finally ?
public List<Item> getItems() throws ItemException {
ArrayList<Item> items = new ArrayList<Item>();
try {
Connection con = ds.getConnection();
try {
PreparedStatement pStmt = con.prepareStatement("SELECT ....");
try {
ResultSet rs = pStmt.executeQuery();
try {
while (rs.next()) {
Item item = new Item();
item.setItemNo(rs.getString("item_id"));
// ...
items.add(item);
}
} finally {
rs.close();
}
} finally {
pStmt.close();
}
} finally {
con.close();
}
} catch (SQLException e) {
throw new ItemException(e);
}
return items;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将其与我的代码进行比较:
close()
如下所示:[编辑] 您需要为其他类型复制此代码。
我还将所有这些移至名为
DBOp
的帮助程序类中,因此我只需重写processRow(ResultSet row)
即可进行实际处理,并且可以省略所有样板代码。在 Java 5 中,DBOp
的构造函数如下:我传入记录器,以便可以显示哪个实例实际上正在轮询数据。
Compare it to my code:
Here is what
close()
looks like:[EDIT] You'll need to copy this code for the other types.
I also moved all this into a helper class called
DBOp
so I just have to overrideprocessRow(ResultSet row)
to do the actual processing and I can omit all that boilerplate code. In Java 5, the constructor ofDBOp
reads:I'm passing in the logger so I can show which instance is actually polling data.
根据 API 文档,语句< /a> 和 结果集 是通过 Connection 隐式关闭的,所以是的 - 其中 2 个 try/finally 块是不必要的(而且非常难看)。当您为大量查询保留单个连接时,显式关闭语句可能会很有用,以减少内存使用。
According to the API doc, Statements and ResultSets are implicitly closed with the Connection, so yes - 2 of those try/finally-blocks are unnecessary (and very ugly). Explicitly closing Statements may be useful when you're keeping a single Connection around for a lot of queries, in order to reduce memory usage.
...并且您不应该在该
getItems()
方法中关闭连接。看起来,您将 Connection 对象存储在该 ds 对象中。因此您应该将其留给ds
来关闭它。否则,存在 ds 使用 getConnection() 方法返回已经关闭的连接的风险,我认为这是一种不需要的和意外的行为;)... and you should not close the connection in that
getItems()
method. It looks like, you stored your Connection object in thatds
object. So you should leave it tods
to close it. Otherwise, there is a risk that ds returns an already closed connection with the getConnection() method, and I assume, that's an unwanted and unexpected behaviour ;)