这是一个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()
当您准备好将更改传播到基础数据源时。但是,如果您正在进行多次更新/插入(针对多行),那么您应该调用 acceptChanges()
毕竟updateRow()
和insertRow()
完成。原因是当您调用 acceptChanges()
时您建立与数据库的实际连接,这通常会很昂贵。因此,每次在多行的 insertRow/updateRow 之后调用它效率不高。
在你的代码中我会输入 acceptChanges()
while block 结束后。原因就是我上面提到的 - 在 while block 中对 cacheResult 进行所有更新后,仅进行一次数据库连接。
关于java - 我们应该将insertRow() 与acceptChanges() 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6684753/