Three methods of using JDBC to get the id of the newly inserted record

In a one-to-many association operation, usually after one party inserts a record, it needs to obtain the id of the current record to facilitate the multi-party insertion operation. To solve this problem, there are at least three different implementation methods in JDBC:
1. Add a query after the insert statement, and use resultset to get the id number
psmt = con.prepareStatement
 

        ("insert into orders (receiver,address,telephone,total,detailnum,userid)values(?,?,?,?,?,?);select

@@identity");
            psmt.setString(1, order.getReceiver());
            ……
            results = psmt.executeQuery();
            if(results.next())
            {
                num = results.getInt(1);
            }
2.利用generatedKey来获取id
psmt = con.prepareStatement
            ("insert into orders (receiver,address,telephone,total,detailnum,userid)values

(?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
            psmt.setString(1, order.getReceiver());
            ……
            psmt.executeUpdate();
            results = psmt.getGeneratedKeys();
            int num = -1;
            if(results.next())
            {
                num = results.getInt(1);
            }

3. Call the stored procedure to achieve, of course, in this case, the properties of the inserted object should not be too many, otherwise the input parameters of the stored procedure are too many. In the stored procedure, return the id as an output parameter
CallableStatement proc = conn.prepareCall("{call proc_insert(?,?,?)}");
            proc.setString(1, cardname);
            proc.setInt(2, money) ;
            proc.registerOutParameter(3, Types.INTEGER);
            proc.execute();
            num = proc.getInt(3)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326446627&siteId=291194637
Recommended