20 April, 2012

Java : Get Last inserted ID (Auto Increment) from Database Query

Really I faced lot of questions & problems related to this topic , basically when we are using mysql as the backend. But its quite obvious & simple for find the last inserted record id (Auto increment ) and primary key also from an insert query ( Not from a procedure). I am not using callable statement for achieve this task. Simple directly by query :-

You can retrive value by using:-

1. select last_insert_id()
2. RETURN_GENERATED_KEYS


Follow the example below:-


String query="insert into m_time_list(vchTime,vchGMT,createdDate) values('"+form.getTxtTime()+"','"+form.getRdbgmt()+"',curdate())";
            pstmt=connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
            sts=pstmt.executeUpdate();   
            rs=pstmt.getGeneratedKeys();
            int sid=0;
            while(rs.next()){
                sid=rs.getInt(1);
            }

Now , Sid contains the return inserted ID.



Hope it will help you.
Ping me:
javadevelopersguide@blogspot.com


No comments:

Post a Comment