MySQL & Java - Get id of the last inserted value (JDBC)
Alternatively you can do:
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getString(1);
}
But use Sean Bright's answer instead for your scenario.
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement
interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero
variable is completely irrelevant and its value is never read after it is set.