Possible duplicate:
How to get insert ID in JDBC?
Hi, I am using JDBC to connect to a database through Java.
Now, I make some insert request, and I need to get the identifier of the last inserted value (so, after stmt.executeUpdate ).
I do not need something like SELECT id FROM table ORDER BY id DESC LIMIT 1 , because I may have problems with concurrency.
I just need to get the id associated with the last insertion (about my instance of Statement).
I tried this, but it doesn't seem to 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, each 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(). 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 :)
java mysql jdbc
markzzz Nov 22 2018-10-22 14:49
source share