【发布时间】:2015-02-25 14:19:30
【问题描述】:
我有一些功能适用于数据库。 我在这里设置了一个 try/catch 用于错误处理,并显示一条消息,它工作正常。
现在调用这个删除函数的类需要知道是否有错误。在我的情况下:如果成功则刷新 GUI,如果失败则什么都不做(因为已经显示了一个消息消息对话框)。
我想出了一个在这个函数中返回布尔值的想法。
public static Boolean delete(int id){
String id2 = Integer.toString(id);
try {
String sql =
"DELETE FROM toDoItem " +
"WHERE id = ?;";
String[] values = {id2};
SQLiteConnection.start();
SQLiteConnection.updateWithPara(sql, values);
} catch (SQLException e) {
Main.getGui().alert("Fail when doing delete in DataBase.");
System.out.println("Exception : "+ e.getMessage());
return false;
}
return true;
}
不知道是好是坏,请告诉。
编辑:
这里是我如何使用的更多细节:
假设上面的代码在 A 类中, B类:
public boolean deleteItem(int id){
int i = index.get(id);
if(theList[i].delete()){ //<---- here is the function from Class A
theList[i] = null;
index.remove(id);
retutn true;
}
retutn false;
}
我需要在不止一个类中传递布尔值,我不知道这是否可以更好地通过......
C 类:
public void toDoList_deleteItem(){
MyButton btn = (MyButton)source;
int id = btn.getRefId();
List toDoList = Main.getToDoList();
if(toDoList.deleteItem(id)){ //<-------function in Class B
Main.getGui().refresh();
}
}
编辑 2:
我注意到这个问题更有可能是在问“我应该如何处理影响 GUI 层的数据库层的异常?”......类似的事情。如果应该编辑问题标题,请纠正我。
【问题讨论】:
-
这取决于你。你会如何处理返回值?
标签: java