jdbcTemplate 插入数据并返回主键id

        String sql = "insert into dc_application (code,name,ip_address,status) value(?,?,?,?)";
        //获取插入数据的自增主键
        KeyHolder holder = new GeneratedKeyHolder();
        template.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, resultArr[0]);
            ps.setString(2, resultArr[1]);
            ps.setString(3, resultArr[2]);
            ps.setByte(4, Byte.parseByte(resultArr[3]));
            return ps;
        }, holder);
        int id = Objects.requireNonNull(holder.getKey()).intValue();
        log.info("数据插入成功,返回的id为:" + id);

 

你可能感兴趣的:(jdbcTemplate 插入数据并返回主键id)