Nic*_*ner 1 java mysql database transactions
我有三个方法,一起将节点保存到数据库.目前,除非所有写入都成功,否则这不会达到不提交更改的预期效果.
conn.setAutoCommit(false);
writeNodeTable(node, newNodeNID);
writeContentTypeBoutTable(node, newNodeNID);
writeTerms(node, newNodeNID);
conn.commit();
Run Code Online (Sandbox Code Playgroud)
如果在第二种或第三种方法中存在问题(例如抛出未捕获的异常),我想回滚所有更改.有什么方法可以使用交易来做到这一点?
这是一个这样的DB写入功能:
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();
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)