0

我有一个带表的 H2 DB

CREATE TABLE income_expense
(
  amount VARCHAR(255) NOT NULL,
  name VARCHAR(255) NOT NULL,
  ondate VARCHAR(255) NOT NULL
);

和一些随机数据,如INSERT INTO income_expense VALUES ('10','Something','2015-04-15');

然后我用JDBC连接到这个数据库并尝试通过CachedRowSet进行更新

public void doUpdate()
{
    try
    { 
        Class.forName("org.h2.Driver");
        setConnection(
                DriverManager.getConnection("jdbc:h2:~/thisdb", "sa", ""));

        CachedRowSet crs2 = new CachedRowSetImpl();
        crs2.setType(CachedRowSet.TYPE_SCROLL_INSENSITIVE);
        crs2.setConcurrency(CachedRowSet.CONCUR_UPDATABLE);
        crs2.setCommand(
                "SELECT amount, name, ondate FROM income_expense");
        crs2.execute(getConnection());
        crs2.absolute(1);
        crs2.updateString("amount", "22");
        crs2.updateString("name"  , "33");
        crs2.updateString("ondate", "44");
        crs2.updateRow();
        crs2.acceptChanges();
    }
    catch (ClassNotFoundException | SQLException e)
    {
        System.out.println("Error occured." + e);
    }
}

此更新失败并显示消息javax.sql.rowset.spi.SyncProviderException: 1 conflict while synchronizing

我在更新记录时做错了什么?

4

1 回答 1

1

好吧... CachedRowSet UPDATE仅在我向表中添加了PRIMARY KEY后才起作用:

ALTER TABLE income_expenses ADD COLUMN id INT NOT NULL AUTO_INCREMENT;
ALTER TABLE income_expenses ADD CONSTRAINT PRIMARY KEY (id);

和指定的列数,这些列形成唯一标识行的键,并将该列包含在 a 中SELECT

//First column from a command will be the key
crs2.setKeyColumns(new int[]{1});
crs2.setCommand("SELECT id, amount, name, ondate FROM income_expense");
于 2015-04-16T12:28:52.957 回答