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); }