在Java中使用PreparedStatementCreator对此方法的解释是什么?

时间:2017-07-13 04:20:31

标签: java mysql class prepared-statement

我从未使用过这个类PreparedStatementCreator,通常当我想执行查询时,我会执行类似:INSERT INTO table (a,b,c...) values (?,?,?...)的操作,但在这种情况下,MySQL查询是:INSERT INTO table() values() ?? < / p> 你能解释一下吗?我无法理解如何跟踪列...

以下代码是方法。提前致谢:

public String add(String identificationNumber, String firstName, String lastName, String email, String cellphone,
            String city, String gender, BloodType bloodType, ShirtSize shirtSize, String emergencyContactName,
            String emergencyContactPhone, String eps, Long birthday, Integer isVolunteer, Group group) {

        PreparedStatementCreator psc = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                String sql = "INSERT INTO participants() VALUES()";
                return con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            }
        };

        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(psc, keyHolder);
        String id = keyHolder.getKey().toString();

        modify(id, identificationNumber, firstName, lastName, email, cellphone, city, gender, bloodType, shirtSize,
                emergencyContactName, emergencyContactPhone, eps, birthday, isVolunteer);

        if (group != null && !Utilities.emptyString(group.getId()))
            setGroup(id, group);

        return id;
    }

public void modify(String id, String identificationNumber, String firstName, String lastName, String email,
            String cellphone, String city, String gender, BloodType bloodType, ShirtSize shirtSize,
            String emergencyContactName, String emergencyContactPhone, String eps, Long birthday, Integer isVolunteer) {
        Object[] args = new Object[] { identificationNumber, firstName, lastName, email, cellphone, city, gender,
                bloodType == null ? null : bloodType.toString(), shirtSize == null ? null : shirtSize.toString(),
                emergencyContactName, emergencyContactPhone, eps, birthday, isVolunteer, id };
        String sql = "UPDATE participants SET identificationNumber = ?, firstName = ?, lastName = ?, email = ?, cellphone = ?, city = ?, gender = ?, bloodType = ?, shirtSize = ?, emergencyContactName = ?, emergencyContactPhone = ?, eps = ?, birthday = ?, isVolunteer=?  WHERE id = ?";

        jdbcTemplate.update(sql, args);
    }

2 个答案:

答案 0 :(得分:0)

您需要更改以下SQL:

  

String sql =“INSERT INTO participant()VALUES()”;

将字段名称添加到participants()并添加?进入VALUES()

然后你需要设置每个?价值通过以下陈述,

ps.setString(1, "test");

每个?你需要设置值。

我希望这对你有用。

答案 1 :(得分:0)

我终于得到了答案,非常简单:

  1. 在表格中插入一行空。
  2. 然后获取该行的ID。
  3. 调用修改为INSERT(真正更新行)。
  4. 这就是全部。