2

这是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()这段代码放在哪里?

4

1 回答 1

3

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

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

于 2011-07-13T19:57:05.900 回答