我正在尝试从模型插入到表中,但是我收到以下错误。
There was an unexpected error (type=Internal Server Error, status=500).
StatementCallback; bad SQL grammar [INSERT INTO user_sample(user_id) VALUES(?); sampleid]; nested exception is java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sampleid' at line
这是我的代码:
public class UserInfo {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
创建了一个表:
CREATE TABLE `user_sample` (
`user_partner_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`user_partner_id`)
) ENGINE=InnoDB AUTO_INCREMENT=77182 DEFAULT CHARSET=utf8;
以下是将数据插入表格的代码。
public void insertValues(@ModelAttribute USerInfo userInfo){
jdbcTemplate.batchUpdate("INSERT INTO user_sample(user_id) VALUES(?)", userInfo.getId());
}
用什么语句从模型插入数据?
答案 0 :(得分:1)
使用Spring Boot,您不需要编写插入manually
,只需利用JPA的强大功能:https://spring.io/guides/gs/accessing-data-jpa/
答案 1 :(得分:0)
如果你想这样做我建议你使用NamedParameterJdbcTemplate
有一个例子,你可以看到它是多么容易:
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
...
@Autowired
private NamedParameterJdbcTemplate jdbcTmpl;
....
public void insertValues(@ModelAttribute USerInfo userInfo){
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO user_sample(user_id) ");
sql.append("VALUES(:userId) ");
Map<String, Object> params = new HashMap<String, Object>();
params.put("userId", userInfo.getId());
jdbcTmpl.update(sql.toString(), params);
}