MySQL & Java - Get id of the last inserted value (JDBC)





import java.sql.*;
public class CoreSeApp {

    public static void main(String[] args) {
        String fname = "Ram Pukar";
        int age = 20;
        int salary = 5000;
        int lastId;
        try {
            //Database Connection.
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db_utility", "root", "");
            String sql = "insert into emp(fname,age,salary) VALUES (?,?,?)";
            PreparedStatement stmt = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1, fname);
            stmt.setInt(2, age);
            stmt.setInt(3, salary);
            int rs = stmt.executeUpdate();
            ResultSet rsLastId = stmt.getGeneratedKeys();
            if(rsLastId.next()){
                lastId=rsLastId.getInt(1);
                System.out.println("Last Inserted Id "+lastId);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
Screen Shot OutPut


Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment