gpt4 book ai didi

java数据访问: is this good style of java data access code,还是尝试太多了?

转载 作者:行者123 更新时间:2023-12-02 11:02:02 28 4
gpt4 key购买 nike

这是一种很好的 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;
}

最佳答案

将其与我的代码进行比较:

Connection con = null;
PreparedStatement pStmt = null;
ResultSet rs = null;
try
{
con = ds.getConnection();
pStmt = con.prepareStatement("SELECT ....");
rs = pStmt.executeQuery();
while (rs.next()) {
Item item = new Item();

item.setItemNo(rs.getString("item_id"));
...

items.add(item);
}
}
finally {
rs = DBUtil.close (rs);
pStmt = DBUtil.close (rs);
con = DBUtil.close (rs);
}

这是 close() 的样子:

public static ResultSet close (ResultSet rs) {
try {
if (rs != null)
rs.close ();
} catch (SQLException e) {
e.printStackTrace ();
// Or use your favorite logging framework.
// DO NOT THROW THIS EXCEPTION OR IT WILL
// HIDE EXCEPTIONS IN THE CALLING METHOD!!
}
return null; // Make sure no one uses this anymore
}

[编辑]您需要为其他类型复制此代码。

我还将所有这些移至名为 DBOp 的帮助程序类中,因此我只需重写 processRow(ResultSet row) 即可进行实际处理,并且我可以省略所有这些样板代码。在 Java 5 中,DBOp 的构造函数如下:

public DBOp (Logger log, DataSource ds, String sql, Object... param)

我传入记录器,以便可以显示哪个实例实际上正在轮询数据。

关于java数据访问: is this good style of java data access code,还是尝试太多了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1938893/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com