JDBC的PreparedStatement獲取自增id

    @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);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章