gpt4 book ai didi

Java Jdbc 事务

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

我需要在 jdbc 中执行选择、更新、插入查询的序列。

这是我的代码:

 public String editRequest(){
connection = DatabaseUtil.getServiceConnection();
try {
connection.setAutoCommit(false);
executeUpdateCategory(category, ticketid);
executeUpdateSubCategory(subcategory,
ticketid);
executeUpdateItem(item, ticketid));
executeUpdateImpact(impact),ticketid));
connection.commit();
response = "Success";
} catch (SQLException e) {
rollback();
}
return response;
}

方法定义:

    public void executeCategory(category,ticketid){
try{
//select query using connection and prepared statement

}
catch(SQLException e){
e.printstacktrace();
}

etc... methods

注意:由于它是单个事务。因此,如果我们在方法中遇到任何异常,它就会执行某些语句。它正在调用 commit() 方法。

但是这些方法是可重用的。有人可以如何捕获 editRequest 方法 catch block 中的异常,以便我可以在出现任何错误时回滚事务吗?

最佳答案

简单答案:重新抛出异常。

示例:

public void executeCategory(category, ticketid) throws SQLException {
try {
//select query using connection and prepared statement
}
catch(SQLException e){
e.printStackTrace();
throw e;
}
}

因此,您可以在异常发生的地方记录异常,然后再次将其抛出到 rollback()

另一种选择(也许是更好的)是创建自定义异常并回滚此自定义异常:

public void executeCategory(category, ticketid) throws CustomException {
try {
//select query using connection and prepared statement
}
catch(SQLException e){
e.printStackTrace();
throw new CustomException(e);
}
}

并在您的调用代码中:

public String editRequest() {
connection = DatabaseUtil.getServiceConnection();
try {
connection.setAutoCommit(false);
executeUpdateCategory(category, ticketid);
// Further calls
connection.commit();
response = "Success";
} catch (CustomException e) {
rollback();
}
return response;
}

关于Java Jdbc 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215875/

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