0
我正在創建一個使用JDBC和MySQL的DAO類。我還沒有收到關於如何關閉標題中列出的項目的任何跡象,但我認爲這是一個很好的做法。現在我認爲這應該在每個CRUD方法中完成,但處理異常似乎有點人爲,我不確定如何實現它。在使用JDBC的DAO類中,這兩種方法中的哪一種處理嘗試捕獲以關閉ResultSet,PreparedStatement和Connection的最佳方法?
第一個例子:
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;
}
在第二個例子中,我需要重複的異常處理。第一個解決方案對我來說似乎更聰明,但我不確定它比第二個解決方案更具可讀性。
設計中是否會採用不僅僅是主觀的約定?
此結構是更可讀,我不知道,我非常感謝你。 但是,我不明白,對於1.7以前的版本,選擇落在開發者身上還是需要採用慣例。 – TheItalianJobless
然後使用第二個選項;這是我更喜歡的,因爲代碼比第一個更清潔。 – ujulu
這是一個很好的答案,但我會更積極地處理'ClassNotFoundException',也許還會''SQLException'。將它們封裝在運行時異常中,因爲這些幾乎總是由不能恢復的部署/編程錯誤(或數據/數據庫問題)引起的。 –