getGeneratedKeys() : auto incremented id field

MySQL

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[]) 
	{  
	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);} 
}
}
The output is here
Data inserted, id  is : 43
43 Test Name 73
MySQL MySQL student table dump


plus2net.com



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-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer