gpt4 book ai didi

java - Java中使用PreparedStatementCreator这个方法的解释是什么?

转载 作者:行者123 更新时间:2023-11-29 18:38:41 25 4
gpt4 key购买 nike

我从未使用过此类PreparedStatementCreator,通常当我想执行查询时,我会执行以下操作:INSERT INTO table (a,b,c...)values(?, ?,?...),但在本例中 MySQL 查询是:INSERT INTO table()values() ??

你能解释一下吗?我无法理解如何跟踪这些列...

下面的代码就是方法。提前致谢:

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

最佳答案

您需要更改以下 SQL:

String sql = "INSERT INTO participants() VALUES()";

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

然后你需要设置每个?通过以下语句计算值,

ps.setString(1, "test");

对于每个?您需要设置值。

我希望这对你有用。

关于java - Java中使用PreparedStatementCreator这个方法的解释是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com