2016-09-19 59 views
0

我想從模型插入表中,但出現以下錯誤。如何在彈簧啓動時從模型插入數據表

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

如果你想這樣做那種方式,我建議你使用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); 
}