zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Xtrabackup的安装
    在 CentOS 7上Virtualbox+phpVirtualBox完整虚拟化环境部署
    用分离、附加的方式实现sql server数据库的备份和还原
    Oracle 11g透明网关连接Sqlserver
    硬盘SMART检测参数详解[转]
    安装了 R2 Integration Servic 之后,SQL Server 2008 Management Studio报错
    jenkins获取git上的源码
    CentOS7配置防火墙
    CentOS 7 安装 Oracle 11.2.0.4
    oralce 11.2.0.4手动创建EM
  • 原文地址:https://www.cnblogs.com/xhwy-1234/p/13948889.html
Copyright © 2011-2022 走看看