2011-07-13 52 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后,仅进行一次数据库连接。