Java Project JSP JDBC Java Program Core Java Demo MORE

How to get last insert id after insert query in JSP


In this example i am going to explain how to get the last insert id of the record.

SQL Query

CREATE TABLE users
(
id int NOT NULL AUTO_INCREMENT,
first_name varchar(50),
last_name varchar(50),
city_name varchar(50),
email varchar(50),
PRIMARY KEY (id)
); 

Here we using 2 files :

  • index.html:for getting the values from the user
  • process.jsp:A JSP file that process the request

index.html

<!DOCTYPE html>
<html>
<body>
<form method="post" action="process.jsp">
First name:<br>
<input type="text" name="first_name">
<br>
Last name:<br>
<input type="text" name="last_name">
<br>
City name:<br>
<input type="text" name="city_name">
<br>
Email Id:<br>
<input type="email" name="email">
<br><br>
<input type="submit" value="submit">
</form>
</body>
</html>

process.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
{
         Class.forName("com.mysql.jdbc.Driver");
           Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
           Statement st=conn.createStatement();
           int i=st.executeUpdate("insert into users(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+"','"+email+"')");
        out.println("Data is successfully inserted!");
        
        
        int id=0;
           ResultSet rs=st.executeQuery("select * from users");
           if(rs.last()){
               id=rs.getInt("id");
           }
           out.println("Last inserted Id: "+id);
        }
        catch(Exception e)
        {
        System.out.print(e);
        e.printStackTrace();
        }
 %>
    

Output

First name:

Last name:

City name:

Email Id: