Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

java - Primary key from inserted row jdbc?

Is there a cross database platform way to get the primary key of the record you have just inserted?

I noted that this answer says that you can get it by Calling SELECT LAST_INSERT_ID() and I think that you can call SELECT @@IDENTITY AS 'Identity'; is there a common way to do this accross databases in jdbc?

If not how would you suggest I implement this for a piece of code that could access any of SQL Server, MySQL and Oracle?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Copied from my code:

pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);

where pInsertOid is a prepared statement.

you can then obtain the key:

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

Hope this gives you a good starting point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...