首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >JDBC的PreparedStatement获取自增id

JDBC的PreparedStatement获取自增id

作者头像
IT云清
发布于 2020-02-17 11:12:19
发布于 2020-02-17 11:12:19
3.5K0
举报
文章被收录于专栏:IT云清IT云清
代码语言:javascript
复制
    @Override
    public void insert(Account account) throws ClassNotFoundException, SQLException {
        account = new Account(100, 1001, new BigDecimal("1000"), new BigDecimal("10"),new BigDecimal("990"));
        Class.forName(properties.getDriverClassName());
        Connection connection = DriverManager
                .getConnection(properties.getUrl(), properties.getUsername(),
                        properties.getPassword());
        String sql = "insert into account(user_id,total,used,residue) values(?,?,?,?)";
        PreparedStatement pst = connection
                .prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//设置自增id
        pst.setLong(1,account.getUserId());
        pst.setBigDecimal(2,account.getTotal());
        pst.setBigDecimal(3,account.getUsed());
        pst.setBigDecimal(4,account.getResidue());
        pst.execute();
        //获取自增id
        long id = 0;
        ResultSet resultSet = pst.getGeneratedKeys();
        if(resultSet.next()){
            id = resultSet.getLong(1);
        }
        LOGGER.info("新增的id为{}",id);
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/02/04 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档