Possible Duplicate:
How to get the insert ID in JDBC?
Hi, I'm using JDBC to connect on database through out Java.
Now, I do some insert query, and I need to get the id of last inserted value (so, after a stmt.executeUpdate).
I don't need something like SELECT id FROM table ORDER BY id DESC LIMIT 1, because I may have concurrency problems.
I Just need to retrieve the id associated to the last insertion (about my instance of the Statement).
I tried this, but seems it doesn't work on JDBC :
public Integer insertQueryGetId(String query) { Integer numero=0; Integer risultato=-1; try { Statement stmt = db.createStatement(); numero = stmt.executeUpdate(query); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()){ risultato=rs.getInt(1); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); errore = e.getMessage(); risultato=-1; } return risultato; } In fact, every time risultato = -1, and I get java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().
How can I fix this problem? Thanks Stackoverflow People :)