JdbcTemplate添加新记录

JdbcTemplate添加新记录并返回id值

static int addUser(final User user) {
        JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());
        jdbc.execute(new ConnectionCallback<Object>() {

            @Override
            public Object doInConnection(Connection con) throws SQLException,
                    DataAccessException {
                String sql = "insert into user(name,birthday, money) values (?,?,?) ";
                PreparedStatement ps = con.prepareStatement(sql,
                        Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, user.getName());
                ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
                ps.setFloat(3, user.getMoney());
                ps.executeUpdate();

                ResultSet rs = ps.getGeneratedKeys();

                int id=0;
                if (rs.next()){
                    id=rs.getInt(1);
                    user.setId(id);
                }
                return id;
            }
        });
        return 0;
    }

你可能感兴趣的:(JdbcTemplate添加新记录)