體驗oracle中的con.commit()

來源:互聯網
上載者:User

建立一個class
package cn.com.cnpc.tz.tetd.workflow;
import java.sql.*;
import cn.com.cnpc.tz.tetd.common.Notes;
import java.sql.Connection;
public class test
{
    public test()
    {
    try {
     jbInit();
       } catch (Exception ex) {
    ex.printStackTrace();
       }

    }
    public static void main(String args[]) {

       Connection con = null;
       try {
    Class.forName(Notes.DRIVER_NAME); //裝載驅動程式
     con = DriverManager.getConnection(Notes.DB_URL,
          "tetdmis", "tetdmis"); //獲得資料庫連接對象
    con.setAutoCommit(false);
    String str = "insert into tetdmis.imagetable values(1,2,null)";
    Statement stmt = con.createStatement();
    int d = stmt.executeUpdate(str);
    System.out.println("插入了" + d + "條");
    ResultSet rs = stmt.executeQuery("select * from imagetable");
    while(rs.next())
    {
        System.out.println("====================");
    }
    con.commit();

    String str1 = "insert into tetdmis.imagetable values(3,4,null)";
    stmt.executeUpdate(str1);
    String dd = null;
    if (dd.equals(""))
    {
        System.out.println("11111111111111111111111111");
    }
    con.commit();

       } catch (Exception e) {
    e.printStackTrace();
    try
    {
        con.rollback();
    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
       }
   }

   private void jbInit() throws Exception {
   }
}

------------------------------------------------------------------------
後台列印出的:
java.lang.NullPointerException

 at cn.com.cnpc.tz.tetd.workflow.test.main(test.java:38)

插入了1條

====================

分析:異常出現在
        if (dd.equals(""))
    {
        System.out.println("11111111111111111111111111");
    }
一旦這裡出現異常,它下面的con.commit()就不會執行,然後,最外面的catch就會con.rollback()
這樣第二次插入的東西就沒有插入進去
-----------------------------------------------------------------------------------------------------
怎樣理解catch與exception
method()
{

try{
try{JJ1();}catch(Exception e1){throw e1;//拋向最外面}
try{JJ2();}catch(Exception e2){throw e2;//拋向最外面}
try{JJ3();}catch(Exception e3){throw e3;//拋向最外面}
}catch(Exception e)
{ e.print(); thow e; //將會交給Exception    }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.