Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last inserted auto increment id in mysql

Tags:

java

mysql

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..

like image 815
Maki92 Avatar asked Jan 05 '13 09:01

Maki92


People also ask

How do I get the last row inserted id in MySQL?

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.

How can we find out which auto increment was assigned on last insert?

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 do I find the last ID of a MySQL database?

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.


4 Answers

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);
like image 142
PermGenError Avatar answered Oct 11 '22 16:10

PermGenError


Try using an alias

rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_id");
like image 23
juergen d Avatar answered Oct 11 '22 14:10

juergen d


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);
}
like image 31
Asad Avatar answered Oct 11 '22 16:10

Asad


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");
like image 44
jlordo Avatar answered Oct 11 '22 16:10

jlordo