I am trying to get the mysql command like mysql_insert_id(); which retrieve the last inserted row\'s auto_increment id. What can I do to get it in Java?
rs =
Try using an alias
rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_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);
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);
}
Another option:
SELECT id FROM table_name ORDER BY id DESC LIMIT 1;
You can use following query to get last auto_incremented ID of last inserted row.
SELECT (max(auto_incr_id)) from table_name;
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");