我使用HSQLDB - Tried版本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.我检查数据库,插入工作。
但是,我在结果集中没有得到任何结果getGeneratedKeys()
它每次都是空的。
我找到了一些用主键替换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(")"));
为什么我没有获得任何生成的密钥?谢谢
// EDIT 如果我用一个insert语句替换我的sqlquery就可以了。
sqlquery = "INSERT INTO BEWERTUNG(TID, JURORID, RUNDE) VALUES(22, 2, 2)";
为什么merge
无法在sqlquery中运行?
答案 0 :(得分:1)
对于高达2.4.0的HSQLDB版本,使用MERGE语句插入数据时生成的密钥不可用。 Code已承诺在下一版本中允许此操作。