getGeneratedKeys() : auto incremented id field


To our student table we will add one more record. Here we have modified out student table and changed the id field to auto increment id field.

more about auto increment ID field.

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[]) 
Connection con=DriverManager.getConnection(  
Statement st=con.createStatement();  
// Adding record 
String query1="INSERT INTO `my_tutorial`.`student` (`name`, `class`, `mark`, `sex`)"
		+ " VALUES ('Test Name', 'Four', '73', 'male')";
ResultSet rs = null;
rs = st.getGeneratedKeys();;
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);;  
System.out.println(rs.getInt(1)+" "+rs.getString("name")+" "+rs.getString("mark"));
}catch(Exception e){ System.out.println(e);} 
The output is here
Data inserted, id  is : 43
43 Test Name 73
MySQL MySQL student table dump


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer