When we insert a record in a table that contains an auto increment column then we can easily obtain its id (primary key).
Below example will show you how you can get the id of last inserted record in MySQL using Java (JDBC). In my example the table has following structure. In this case id column is auto increment primary key.
How to Get Last Inserted Record ID in MySQL Using Java (JDBC)
import java.sql.*; public class MySQLJavaExample { static int getLastId(){ String URL="localhost:3306"; String USERNAME="root"; String PASSWORD="root"; String DATABASE="demo"; int id=0; try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://"+ URL + "/" + DATABASE,USERNAME,PASSWORD); PreparedStatement ps=con.prepareStatement("insert into record (name) values(?)",Statement.RETURN_GENERATED_KEYS); ps.setString(1,"Neeraj"); ps.executeUpdate(); ResultSet rs=ps.getGeneratedKeys(); if(rs.next()){ id=rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return id; } public static void main(String args[]){ System.out.println("id:"+getLastId()); } }
Output:
id: 3
If you have any doubts regarding above code then you can ask it by commenting below.
What if my last insertion is more than 1 row ? How do I retrieve more than 1 Id ?
Thanks for sharing! It was useful
Thanks a lot for your explanation, worked at first try.