gpt4 book ai didi

java - 使用 with 参数时 JdbcTemplate 更新错误

转载 作者:行者123 更新时间:2023-11-30 08:54:08 25 4
gpt4 key购买 nike

我正在编写 SpringMVC 数据库应用程序。当我尝试使用带参数的 JdbcTemplate 对象更新方法将数据插入数据库时​​,我在插入数据时出错。没有参数编码如下:

String sql = "INSERT INTO contact (name, email, address, telephone)"
+ " VALUES ('" + contact.getName() + "', '" + contact.getEmail() + "', '"
+ contact.getAddress() + "', '" + contact.getTelephone() + "')";
jdbcTemplate.update(sql);

但是当我使用 with 参数时,出现错误:

String sql = "INSERT INTO contact (name, email, address, telephone)"
+ " VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
contact.getAddress(), contact.getTelephone());

请帮帮我!

最佳答案

您必须指定参数。检查以下示例。

//insert with named parameter
public void insertNamedParameter(Customer customer){

String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)";

Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("custId", customer.getCustId());
parameters.put("name", customer.getName());
parameters.put("age", customer.getAge());

getSimpleJdbcTemplate().update(sql, parameters);

}

您可以引用以下链接以供引用。

Spring Named Parameters examples in SimpleJdbcTemplate

关于java - 使用 with 参数时 JdbcTemplate 更新错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29533937/

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