Get last inserted auto increment id in mysql

see this post for answer & explanation

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getInt(1);
}

Why not

SELECT MAX(id) FROM schedule

If id your column has a different name than id, you need to replace it accordingly in the above query.

You can use it like:

rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");

Using JDBC, you can use Connection.PreparedStatement(query, int) method.

PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
pstmt.executeUpdate();  
ResultSet keys = pstmt.getGeneratedKeys();    
keys.next();  
key = keys.getInt(1);

Try using an alias

rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_id");

Tags:

Mysql

Java