插入行jdbc的主键?

Oma*_*eji 40 java identity jdbc

是否有跨数据库平台方式来获取刚刚插入的记录的主键?

我注意到这个答案说你可以通过Calling得到它SELECT LAST_INSERT_ID(),我认为你可以调用SELECT @@IDENTITY AS 'Identity';有一种常见的方法在jdbc中的数据库中做这个吗?

如果不是,你会如何建议我为一段可以访问任何SQL Server,MySQL和Oracle的代码实现这个?

ext*_*eon 53

复制自我的代码:

pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);
Run Code Online (Sandbox Code Playgroud)

其中pInsertOid是一个预准备语句.

然后你可以获得密钥:

// fill in the prepared statement and
pInsertOid.executeUpdate();
ResultSet rs = pInsertOid.getGeneratedKeys();
if (rs.next()) {
  int newId = rs.getInt(1);
  oid.setId(newId);
}
Run Code Online (Sandbox Code Playgroud)

希望这能为您提供一个良好的起点.


atr*_*thi 23

extraneon的答案虽然正确,但对甲骨文不起作用.

您为Oracle执行此操作的方式是:

String key[] = {"ID"}; //put the name of the primary key column

ps = con.prepareStatement(insertQuery, key);
ps.executeUpdate();

rs = ps.getGeneratedKeys();
if (rs.next()) {
    generatedKey = rs.getLong(1);
}
Run Code Online (Sandbox Code Playgroud)