2011-07-13 87 views
1

這是Java中的示例代碼:我們應該使用insertRow()和acceptChanges()嗎?

try { 
     /* create connection */ 
     Connection conn = DriverManager.getConnection(url, username, password); 
     Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); 

     /* create a CachedRowSet */ 
     CachedRowSet cachedResult = new com.sun.rowset.CachedRowSetImpl(); 

     /* set connection information */ 
     cachedResult.setUrl(url); 
     cachedResult.setUsername(username); 
     cachedResult.setPassword(password); 

     ResultSet result = stmt.executeQuery("SELECT * FROM tbl"); 

     /* populate CachedRowSet */ 
     cachedResult.populate(result); 

     /* close connection */ 
     result.close(); 
     stmt.close(); 
     conn.close(); 

     /* now we edit CachedRowSet */ 
     while (cachedResult.next()) { 
      if (cachedResult.getInt("id") == 12) { 
       cachedResult.moveToInsertRow(); 

       /* use some updateXXX() functions */ 

       cachedResult.insertRow(); 
       cachedResult.moveToCurrentRow(); 
      } 
     } 
    } catch (SQLException e) { 
     e.printStackTrace(); 
} 

現在我的問題是這樣的:1。 我應該使用insertRow()?或者我應該用acceptChanges()代替?或者兩者兼得? 2.我應該在這個代碼中放置acceptChanges()

回答

2

當您準備將更改傳播到基礎數據源時,請致電acceptChanges()。但是,如果您正在執行多個更新/插入(對於多行),則應在完成所有updateRow()insertRow()完成後致電acceptChanges()。原因是當你調用acceptChanges()時,你建立了一個通常很昂貴的與數據庫的實際連接。所以每次在每行insertRow/updateRow之後調用它對於多行來說效率不高。

在你的代碼中,我會在while塊結束後放acceptChanges()。原因是我上面提到的 - 在所有更新完成到while塊中的cacheResult後,僅進行一次數據庫連接。