Java 我们应该将insertRow()与acceptChanges()一起使用吗?

Java 我们应该将insertRow()与acceptChanges()一起使用吗?,java,jdbc,resultset,cachedrowset,Java,Jdbc,Resultset,Cachedrowset,以下是java中的示例代码: try { /* create connection */ Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

以下是java中的示例代码:

    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()
放在这段代码中的什么位置?

当您准备将更改传播到基础数据源时,可以调用
acceptChanges()
。但是,如果要执行大量更新/插入(针对多行),那么在完成所有的
updateRow()
insertRow()
之后,应该调用
acceptChanges()
。原因是当您调用
acceptChanges()
时,您建立了到数据库的实际连接,这通常会很昂贵。因此,每次在多行的每个insertRow/updateRow之后调用它是没有效率的

在您的代码中,我会在while块结束后放入
acceptChanges()
。原因就是我上面提到的——在while块中对cacheResult进行了所有更新之后,只进行一次数据库连接