我在用CachedRowSet。但是,当我调用insertRow()方法时,插入行的SQLException失败。
这是我的代码:
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/javapos";
static final String USERNAME = "root";
static final String PASSWORD = "sbc";
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 uom order by itemid");
rs.execute();
while(rs.next()){
System.out.println(rs.getString("itemid") + " - " + rs.getString("uom"));
}
rs.moveToInsertRow();
rs.updateString(2,"Sample code");
rs.insertRow();
rs.moveToCurrentRow();
rs.acceptChanges();
}发布于 2014-09-13 11:32:57
调用insertRow()时,CachedRowSet的引用实现将执行一次检查,检查是否已填充了所有必需的列,否则会引发异常(来自CachedRowSet.insertRow()的源,行号不完全匹配):
if (onInsertRow == false ||
insertRow.isCompleteRow(RowSetMD) == false) {
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.failedins").toString());
}检查是在InsertRow.isCompleteRow(RowSetMetaData)中执行的
public boolean isCompleteRow(RowSetMetaData RowSetMD) throws SQLException {
for (int i = 0; i < cols; i++) {
if (colsInserted.get(i) == false &&
RowSetMD.isNullable(i + 1) == ResultSetMetaData.columnNoNulls) {
return false;
}
}
return true;
}换句话说,当插入行时,必须为所有不可空的列提供一个值(这包括主键)。解决这一问题的方法似乎有两种:
null显式地将列设置为updateNull。使用setNull不起作用:它提供了相同的错误,使用setObject(idx, null)会导致NullPointerException在使用这些更改的代码时,当调用SQLException时,我会得到一个acceptChanges,因为实现没有禁用autoCommit (似乎是评论掉),但是它确实显式地调用了commit (在autoCommit中是无效的)。这似乎并不容易解决,除非可能显式地在execute上提供连接,或者创建自己的实现。
我认为这类问题实际上证明了RowSet实现实际使用的很少(否则它们早就被排除在外了)。
但是请注意,如果这是您需要的实际代码,并且不需要CachedRowSet的断开连接特性,那么您可以简单地使用一个可更新的结果集。
发布于 2022-08-24 09:09:02
示例:
beginAddRow(crs);
crs.updateString("TABLE_TYPE", "TABLE");
continueAddRow();
crs.updateString("TABLE_TYPE", "INDEX");
endAddRow(); static public CachedRowSet beginAddRow(CachedRowSet crs) throws SQLException {
crs.moveToInsertRow(); // onInsertRow = true
return crs;
}
static public CachedRowSet continueAddRow(CachedRowSet crs) throws SQLException {
crs.insertRow();
crs.moveToCurrentRow();
crs.moveToInsertRow();
return crs;
}
static public CachedRowSet endAddRow(CachedRowSet crs) throws SQLException {
crs.insertRow();
crs.moveToCurrentRow(); // onInsertRow = false;
crs.beforeFirst();
return crs;
}https://stackoverflow.com/questions/25819496
复制相似问题