Getting the last inserted record id of a database table in java

Getting the last inserted record id of a database table in java

The new JDBC-3.0 method getGeneratedKeys() which is now the preferred method to use if you need to retrieve AUTO_INCREMENT keys.
PreparedStatement ps = con.prepareStatement("insert into emp values(?,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, e.getId());
            ps.setString(2, e.getName());
            ps.executeUpdate();
            ResultSet rset = ps.getGeneratedKeys();
           while (rset.next()) {
           int i = rset.getInt(1);
           System.out.println("key=" + i);
            }

Another way

PreparedStatement ps=con.prepareStatement("insert into emp values(?,?)");
            ps.setInt(1,e.getId());
            ps.setString(2,e.getName());
            ps.executeUpdate();
            Statement stmt = con.createStatement();
            ResultSet rset = stmt.executeQuery("SELECT last_insert_id()");
            while (rset.next()) {
            System.out.println("key="+rset.getInt(1));
            }

Database Table

CREATE TABLE `emp` (
 `eid` int(11) NOT NULL auto_increment,
 `ename` varchar(20) default NULL,
 PRIMARY KEY  (`eid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

No comments:

Post a Comment