gpt4 book ai didi

java - 嵌套事务回滚时出现"java.sql.SQLException: SAVEPOINT _667166fe_13ab4b3e3de__8000 does not exist"异常?

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:00 26 4
gpt4 key购买 nike

类用户{

public static void main(String arg[]) throws SQLException {
Connection con = DBConnect.getConnection();
con.setAutoCommit(false);
PreparedStatement pstmt;
System.out.println(con.getMetaData().supportsSavepoints()); // true
try {
pstmt = con.prepareStatement("insert into emp(emp_id, emp_name, salary, address, contact_number)values(?,?,?,?,?)");
pstmt.setInt(1, 1);
pstmt.setString(2, "a");
pstmt.setDouble(3, 8);
pstmt.setString(4, "s");
pstmt.setInt(5, 9);
pstmt.executeUpdate();
con.commit();
Savepoint sp = con.setSavepoint();
if (myMethod(con)) {
/**
* I want to rollback the nested transaction if any error occur
*/
con.rollback(sp);
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static boolean myMethod(Connection con) throws SQLException {

PreparedStatement pstmt;
try {
pstmt = con.prepareStatement("insert into emp(emp_id, emp_name, salary, address, contact_number)values(?,?,?,?,?)");
pstmt.setInt(1, 2);
pstmt.setString(2, "G");
pstmt.setDouble(3, 8);
pstmt.setString(4, "G");
pstmt.setInt(5, 10);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}

在上面的代码中,我想在任何条件失败时回滚嵌套事务。我在提交第一笔交易后创建了一个保存点。我收到一个异常

java.sql.SQLException: SAVEPOINT _667166fe_13ab4b3e3de__8000 does not exist
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2988)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:935)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:873)
at com.mysql.jdbc.Connection.rollback(Connection.java:4777)
at com.User.main(User.java:31)

我想知道嵌套事务会不会回滚?

最佳答案

由于您已经在调用 con.commit(); 之前和之后(在 myMethod() 方法中)Savepoint sp = con.setSavepoint();,所以有没有保存点,因此提示。

COMMIT 删除所有保存点。 请引用此处的文档:

  1. > Oracle SAVEPOINT Statement
  2. > SQLite Save Point

如果要设置保存点,请删除commit 调用。

在您代码的当前状态下,如果成功,所有事务都已提交,因此无法回滚。

关于java - 嵌套事务回滚时出现"java.sql.SQLException: SAVEPOINT _667166fe_13ab4b3e3de__8000 does not exist"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150626/

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