gpt4 book ai didi

java - CachedRowSet 插入行失败

转载 作者:行者123 更新时间:2023-11-30 03:45:34 25 4
gpt4 key购买 nike

我正在使用CachedRowSet。但是当我调用 insertRow() 方法时,出现 SQLException failed to insert row。

这是我的代码:

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();
}

最佳答案

当您调用 insertRow() 时,CachedRowSet 的引用实现会检查是否已填充所有必需的列,否则会引发异常(来源来自 Grepcode 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;
}

换句话说,插入行时,您必须为所有不可为空的列(包括主键)提供一个值。似乎有两种方法可以解决这个问题:

  • 设置一个(随机)值。这确实要求始终生成您的主键(即使提供了值)。
  • 使用 updateNull 将列显式设置为 null。使用 setNull 不起作用:它会提供相同的错误,并且使用 setObject(idx, null) 会导致 NullPointerException

当使用您的代码进行这些更改时,我在调用 acceptChanges 时收到 SQLException ,因为该实现不会禁用 autoCommit (似乎已经是 commented out ),但它确实显式调用 commit (在 autoCommit 中时无效)。这似乎不容易解决,除非在 execute 上显式提供连接,或者创建您自己的实现。

我认为这类问题实际上表明了 RowSet 实现的实际使用量有多么少(否则它们早就被淘汰了)。

但请注意,如果这是您需要的实际代码,并且不需要 CachedRowSet 的断开连接特征,那么您可以简单地使用可更新的结果集。

关于java - CachedRowSet 插入行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com