Java-JDBC操作事务
1、开启事务(关闭自动提交则默认开启事务)
conn.setAutoCommit(false);
2、一组业务执行完毕,提交事务
conn.commit();
3、可以在catch语句中显示的定义回滚语句,但默认失败就会回滚
conn.rollback();
示例:
package com.test.third;
import com.test.second.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TransactionTest {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 关闭自动提交(开启事务)
conn.setAutoCommit(false);
String sql1 = "update `account` set money = money - ? where `id` = ?";
st = conn.prepareStatement(sql1);
st.setInt(1,100);
st.setInt(2,1);
st.executeUpdate();
String sql2 = "update `account` set money = money + ? where `id` = ?";
st = conn.prepareStatement(sql2);
st.setInt(1,100);
st.setInt(2,2);
st.executeUpdate();
// 提交事务
conn.commit();
System.out.println("构建成功");
} catch (SQLException e) {
try {
// 失败则回滚
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}