我使用 HSQLDB - 尝试过版本 2.3.4 和 2.4。
我有这个Java代码:
String sqlquery = "MERGE INTO bewertung pu USING "
.concat("(VALUES ?,?,?) ")
.concat("temp (tid,jurorid,runde) ")
.concat("ON temp.tid = pu.tid and temp.jurorid=pu.jurorid and temp.runde=pu.runde ")
.concat("WHEN NOT MATCHED THEN ")
.concat("INSERT (tid,jurorid,runde) ")
.concat("VALUES (temp.tid,temp.jurorid,temp.runde)");
PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1, eineBewertung.getTanzID()); //TID
preparedStatement.setInt(2, eineBewertung.getJurorID()); //JURORID
preparedStatement.setInt(3, eineBewertung.getRunde()); //RUNDE
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected == 0) {
//UPDATE
//DO SOMETHING
}else{
//INSERT
try (ResultSet rs = preparedStatement.getGeneratedKeys()) {
if (rs.next()) {
eineBewertung.setBewertungsid(rs.getInt(1));
}
}catch (SQLException ex) {
this.controller.error_ausgeben(ex);
}
}
它有效。如果我插入一个新行,我会得到 rowsAffected
= 1。我检查数据库并且插入有效。
但是,我在结果集中没有得到任何内容 getGenerateKeys()
每次都是空的。
我发现了一些用主键替换 Statement.RETURN_GENERATED_KEYS
的提示。但这对我不起作用。
PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
new String[]{"BEWERTUNGSID"});
这就是我创建表格的方式:
statement.execute("create table PUBLIC.BEWERTUNG"
.concat("(BEWERTUNGSID INTEGER IDENTITY,")
.concat("TID INTEGER FOREIGN KEY REFERENCES Tanz(Tanzid),")
.concat("JURORID INTEGER not null FOREIGN KEY References JUROR(JURORID),")
.concat("RUNDE INTEGER not null,")
.concat("primary key(BEWERTUNGSID)")
.concat(")"));
为什么我没有取回任何生成的 key ?谢谢
//编辑 如果我用插入语句替换 sqlquery,它就可以工作。
sqlquery = "INSERT INTO BEWERTUNG(TID, JURORID, RUNDE) VALUES(22, 2, 2)";
为什么 merge
在 sqlquery 中不起作用?
最佳答案
对于 HSQLDB 2.4.0 及以下版本,使用 MERGE 语句插入数据时生成的键不可用。代码已 promise 在下一版本中允许这样做。
关于java - 尽管插入了行,但 Get generatedKeys 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617508/