gpt4 book ai didi

Java:回滚数据库更新?

转载 作者:搜寻专家 更新时间:2023-10-30 21:43:18 25 4
gpt4 key购买 nike

我有三种方法,它们一起将节点保存到数据库中。目前,这没有达到不提交更改的预期效果,除非所有写入都成功。

    conn.setAutoCommit(false);
writeNodeTable(node, newNodeNID);
writeContentTypeBoutTable(node, newNodeNID);
writeTerms(node, newNodeNID);
conn.commit();

如果第二种或第三种方法出现问题(比如抛出未捕获的异常),我想回滚所有的更改。有什么方法可以使用事务来做到这一点吗?

这是一个这样的数据库写入函数:

private void writeTerms(DrupalNode node, int newNodeNID) throws SQLException {
String sql = "INSERT INTO term_node (nid, vid, tid) VALUES (?, ?, ?)";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, newNodeNID);
prep.setInt(2, newNodeNID);

String schoolName = termHelp.schoolOfAgainst(node.get(BoutField.against));
prep.setString(3, schoolName);

prep.execute();

String fencerName = termHelp.fencerOfAgainst(node.get(BoutField.against));
prep.setString(3, fencerName);
prep.execute();
prep.close();
}

最佳答案

Upul 是正确的,您需要实现 Connection.setAutoCommit(false)Connection.rollback() 方法。您可能想为每笔交易尝试的一件事是拥有这种流程:

Connection conn = null; // or have the connection sent in
try {
conn = getConnection(username, password);
conn.setAutoCommit(false);
// do stuff with connection
conn.commit();
} catch (SQLException sqle) {
// handle error appropriately
conn.rollback();
} finally {
// cleanup
conn.close(); // depends on when the connection was allocated
}

关于Java:回滚数据库更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130064/

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