我正在创建一个使用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;
}
设计中是否有不只是主观的约定?