• 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
  • 相关阅读:
    smart client优势在那里? (草稿)
    MSN to expand free email storage to 250MB
    转移阵地了,新地址:http://spaces.msn.com/members/PuGong
    关于XMLHTTP object的OPEN方法
    创建第一个Windows Phone应用程序(一)
    Windows 平台下安装Cygwin后,sshd服务无法启动
    ASP.NET MVC3 Use Remote Validation
    ASP.NET MVC3中使用AllowHtml attribute
    HTML5 Canvas实现简单的俄罗斯方块
    创建第一个Windows Phone应用程序(二)
  • 原文地址:https://www.cnblogs.com/xhwy-1234/p/13948889.html
Copyright © 2020-2023  润新知