如何正确获取last_insert_id

今天尝试通过

select last_insert_id()

 来获取last insert id,但客户端打点发现结果不对:

lastrowid= 111654761    INSERT INTO `message_message2tag` (`tag_id`, `message_id`) VALUES (?, ?)
lastrowid= 111654762    INSERT INTO `message_message2tag` (`tag_id`, `message_id`) VALUES (?, ?)
lastrowid= 111654763    INSERT INTO `message_message2tag` (`tag_id`, `message_id`) VALUES (?, ?)
lastrowid= 111654764    INSERT INTO `message_message2tag` (`tag_id`, `message_id`) VALUES (?, ?)
lastrowid= 38968438    INSERT INTO `search_needtoindex` (`oid`, `otype`, `is_delete`) VALUES (?, ?, ?)
lastrowid= 38968438    INSERT INTO `message_messagecontent` (`id`, `msg`) VALUES (?, ?)
lastrowid= 94356472    INSERT INTO `mblog_star` (`user_id`, `count`, `object_id`, `add_datetime`, `category`) VALUES (?, ?, ?, ?, ?)
lastrowid= 94356473    INSERT INTO `mblog_star` (`user_id`, `count`, `object_id`, `add_datetime`, `category`) VALUES (?, ?, ?, ?, ?)
lastrowid= 63628816    INSERT INTO `broadcast_status` (`user_id`, `object_id`, `add_datetime`, `category`) VALUES (?, ?, ?, ?)
remote gfw http://192.168.172.9:7788/fdb/match/ taking 5 ms at 04-06 22:03:09
lastrowid= 71250683    INSERT INTO `message_message` (`recipient_id`, `sender_id`, `group_id`, `album_id`, `parent_id`, `reply_count`, `favorite_count`, `like_count`, `flag`, `last_replied_datetime`, `add_datetime`, `gmt_updated`, `buyable`, `photo_id`, `status`, `category`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

尝试使用spring jdbc GeneratedKeyHolder
KeyHolder keyHolder = new GeneratedKeyHolder();
            writeJdbc.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                    PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                    for (int i = 0; i < params.length; ++i) {
                        ps.setObject(i + 1, params[i]);
                    }
                    return ps;
                }

            }, keyHolder);

            return keyHolder.getKey().longValue();
 

你可能感兴趣的:(insert)