美文网首页
正确书写事务代码

正确书写事务代码

作者: 小知大知 | 来源:发表于2018-05-09 11:52 被阅读4次
      public static void main(String[] args) {
           Connection conn = null;
           Statement stmt = null;
           try {
               // 动态导入数据库的驱动
               Class.forName("com.mysql.jdbc.Driver"); 
               // 获取数据库链接
               conn = DriverManager.getConnection(
                      "jdbc:mysql://localhost:3306/employee", "root", "wang314159");          
               // 开启事务
               //不把其设置为true之前都是一个当作一个事务来处理
               conn.setAutoCommit( false );
     
               // 创造SQL语句
               String sql = "INSERT INTO myrollback ( name,age,address,school ) VALUES ( 'test', 22,'大立即','hdu' )";           
               String sql2 = "INSERT INTO myrollback ( name,age,address,school ) VALUES ( 'test_Name', '33','大立即','hdu' ,'test')";
               // 执行SQL语句
               stmt = conn.createStatement();
               stmt.executeUpdate(sql);
               stmt.executeUpdate(sql2);
               // 提交事务
               conn.commit();
               System.out.println( "OK!" );
           } catch (Exception e) {
               e.printStackTrace();
               System.out.println("有错误!");
              
               try {
              // 回滚事务
              //撤销上面对事务的所有操作哈!
                  conn.rollback();
               } catch ( Exception e2 ) {}
           } finally {
               // 关闭Statement
               try {
                  stmt.close();
               } catch (Exception e) {}
               // 关闭Connection
               try {
                  conn.close();
               } catch (Exception e) {}
           }
        }
    }
    

    相关文章

      网友评论

          本文标题:正确书写事务代码

          本文链接:https://www.haomeiwen.com/subject/riowlftx.html