JDBC-事务提交机制

// JDBC中事务提交机制默认是只要执行一次DML语句则自动提交一次;
//但是实际业务当中,通常都是N条DML语句共同联合才能完成的,
// 必须保证他们这些DML语句在同一个事务中同时成功或者同时失败
import java.sql.*;
public class JdbcTest09 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/firstbase", "root", "123456");
            con.setAutoCommit(false); //关闭自动提交机制,也就是把自动提交改为手动提交(开启事务)
            String sql = "update  t_user set userName = ? where id = ?";
            ps = con.prepareStatement(sql);
            ps.setString(1,"lili");
            ps.setInt(2,2);
            int count = ps.executeUpdate();
            System.out.println(count);  //可以得到这里是1,说明已经执行成功了;但是实际业务当中,通常都是N条DML语句共同联合才能完成的,
            // 必须保证他们这些DML语句在同一个事务中同时成功或者同时失败

            //第二次传值
            ps.setString(1,"lilei");
            ps.setInt(2,3);
            ps.executeUpdate();

            con.commit();  // 提交事务

        } catch (Exception e) {
            if (con != null){
                try {
                    con.rollback(); // 如果一个事务执行中出现异常要通过回滚来恢复数据
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {

            if (ps != null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (con != null){
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

When nothing seems to help, I go look at a stonecutter hammering away at his rock, perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it, but all that had gone before. -- Jacob Riis
原文地址:https://www.cnblogs.com/xhwy-1234/p/13948889.html