码迷,mamicode.com
首页 > 数据库 > 详细

jdbc-transaction

时间:2017-10-16 16:44:42      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:com   try   padding   host   insert   bshare   cat   rgs   span   

public static void main(String[] args) {

       Connection conn=null;

       Statement stmt=null;

       try {

           Class.forName("oracle.jdbc.driver.OracleDriver");

          conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","123456");

          stmt=conn.createStatement();

//首先用Connection中的setAutoCommit方法将自动commit设为false,因为JDBC默认是自动commit,执行完所要 执行的语句块后再用Connection的commit方法提交,完成后setAutoCommit(true),恢复JDBC的默认设置
           conn.setAutoCommit(false);

           stmt.addBatch("insert into dept2 values(50,‘Game‘,‘Shanghai‘)");

           stmt.addBatch("insert into dept2 values(60,‘Game‘,‘Shanghai‘)");

           stmt.addBatch("insert into dept2 values(70,‘Game‘,‘Shanghai‘)");

           stmt.executeBatch();

           conn.commit();

          conn.setAutoCommit(true);
       } catch (ClassNotFoundException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }catch(SQLException e){

           e.printStackTrace();   

//捕捉到任何的SQLException立刻rollback,然后恢复JDBC的默认设置
          try{

              if(conn!=null){

                  conn.rollback();

                  conn.setAutoCommit(true);

              }

           }catch(SQLException e1){

              e1.printStackTrace();

           }

       }finally{

           try {

              if(stmt!=null)

              stmt.close();

              }catch (SQLException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

           try {

              if(conn!=null)

              conn.close();

              }catch (SQLException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }            

       }

    }

jdbc-transaction

标签:com   try   padding   host   insert   bshare   cat   rgs   span   

原文地址:http://www.cnblogs.com/371610785qq/p/7676891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!