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 = st.executeQuery("select last_insert_id() from schedule");
lastid = rs.getString("last_insert_id()");
my lastid was declared as INT. I dono what to use in rs.get and also the parameter..
MySQL LAST_INSERT_ID() Function The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.
Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.
How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.
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");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With