我正在使用CachedRowSetImpl,我可以从数据库获取数据,但无法插入。
这是代码:
public class NewClass {
static final String DATABASE_URL = "jdbc:derby://localhost:1527/TaskDB;create=true";
static final String USERNAME = "user";
static final String PASSWORD = "user";
public static void main (String [] agr) throws SQLException
{
CachedRowSetImpl rs = new CachedRowSetImpl();
rs.setUrl(DATABASE_URL);
rs.setUsername(USERNAME);
rs.setPassword(PASSWORD);
rs.setCommand("SELECT * FROM TASKTABLE");
rs.execute();
rs.moveToInsertRow();
rs.updateString("Column_Name","DataString");
rs.insertRow();
rs.moveToCurrentRow();
rs.updateRow();
}
}
它抛出异常:
Exception in thread "main" java.sql.SQLException: Failed on insert row at com.sun.rowset.CachedRowSetImpl.insertRow(CachedRowSetImpl.java:5462) at NewClass.main(NewClass.java:32)
我尝试过 JdbcRowSetImpl 而不是 CachedRowSetImpl ,并且工作正常
更新:我使用此代码来捕获有关异常的更多详细信息:
catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
输出是:
SQLState:null
Error Code:0
Message:Failed on insert row
最佳答案
我遇到了与您相同的问题,但我将 acceptChanges(cnnt)
放在抛出异常的末尾,如 API 所述。
...
cachedSet.moveToInsertRow();
cachedSet.updateInt(1,12);
cachedSet.updateString(2,"Joe");
cachedSet.updateString(3,"abcde");
cachedSet.insertRow();
cachedSet.moveToCurrentRow();
cachedSet.acceptChanges(cnnt);
......
如果我在没有最后一个行(acceptChanges(cnnt))
的情况下运行它,则不会抛出任何异常,但数据库不会更新。
如果我用最后一个运行它,将会出现与您相同的异常。
我查了一下,从API中得到了acceptChanges()
的文档:
SQLException - if the cursor is on the insert row
我查看了insertRow()
的文档:
SQLException - if a database access error occurs; the result set concurrency is CONCUR_READ_ONLY, this method is called on a closed result set, if this method is called when the cursor is not on the insert row, or if not all of non-nullable columns in the insert row have been given a non-null value
也许你能从中得到一些东西。
关于java - 使用 CachedRowSet 插入行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596022/