jdbc-transaction

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdbc-transaction相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章