Now while adding the record we will not specify the id field as MySQL will generate the key and add to the ID field along with the other data. This key or id is the next increment value ( based on the just previous id value ).
Once the record is added MySQL will return us the Key or Id value to our ResultSet by using getGeneratedKeys()
After adding the record, to check the data we will use the same ID to get the row details.
import java.sql.*;
public class my_connect {
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_tutorial","root","test");
Statement st=con.createStatement();
// Adding record
String query1="INSERT INTO `my_tutorial`.`student` (`name`, `class`, `mark`, `sex`)"
+ " VALUES ('Test Name', 'Four', '73', 'male')";
st.executeUpdate(query1);
ResultSet rs = null;
rs = st.getGeneratedKeys();
rs.next();
int new_id=rs.getInt(1);
System.out.println("Data inserted, id is : "+ new_id);
// Display the record just now inserted.
rs=st.executeQuery("SELECT * FROM STUDENT WHERE id="+new_id);
rs.next();
System.out.println(rs.getInt(1)+" "+rs.getString("name")+" "+rs.getString("mark"));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}