MySQL -> JDBC操作事务
ACID
- 代码实现
1.开启事务
2.一组业务执行完毕,提交事务
3.可以在catch语句中显示定义回滚rollback语句,但默认失败就会回滚
import com.anobabe.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestTransaction2 {
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 -100 where name = 'A'";
st = conn.prepareStatement(sql1);
st.executeUpdate();
//int x = 1/0; //报错
String sql2 = "update account set money = money +100 where name = 'B'";
st = conn.prepareStatement(sql2);
st.executeUpdate();
//业务完毕,提交事务
conn.commit();
System.out.println("成功!");
} catch (SQLException throwables) {
//如果失败则默认回滚
// try{
// conn.rollback();
// } catch (SQLException e) {
// e.printStackTrace();
// }
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}