【发布时间】:2018-03-01 18:32:40
【问题描述】:
我正在创建一个使用 JDBC 和 MySQL 的 DAO 类。我没有收到有关如何关闭标题中列出的项目的任何指示,但我读到这样做是一种好习惯。现在我认为这应该在每个 CRUD 方法中完成,但是处理异常似乎有点人为,我不确定如何实现它。
第一个例子:
public boolean update2(Dto dto) {
assert dto != null;
if (readById(dto.getId()).getId() == 0) {
throw new RuntimeException("Row with this id doesn't exist");
}
boolean flag = false;
try {
Connection connection = DAOFactory.createConnection();
String sql = "SQL statement";
try {
PreparedStatement ps = connection.prepareStatement(sql);
try {
// Some stuff with preparedstatement
ps.executeUpdate();
flag = true;
} finally {
if (ps != null) ps.close();
}
} finally {
if (connection != null) connection.close();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
第二个例子:
public boolean update(Dto dto) {
assert dto != null;
if (readById(dto.getId()).getId() == 0) {
throw new RuntimeException("Row with this id doesn't exist");
}
boolean flag = false;
PreparedStatement ps = null;
Connection connection = null;
try {
connection = DAOFactory.createConnection();
String sql = "SQL statement";
ps = connection.prepareStatement(sql);
// Some stuff with preparedstatement
ps.executeUpdate();
flag = true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return flag;
}
在第二个示例中,我需要重复异常处理。第一个解决方案对我来说似乎更聪明,但我不确定它是否比第二个更具可读性。
设计中是否有不仅是主观的约定?
【问题讨论】:
标签: java jdbc exception-handling dao