How to Get Last Inserted Record ID in MySQL Using Java (JDBC)

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

 

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.

3 thoughts on “How to Get Last Inserted Record ID in MySQL Using Java (JDBC)”

Leave a Comment

Your email address will not be published. Required fields are marked *