2017-07-31 62 views
1

我向Rest Controller發送了一個POST請求。JdbcTemplate更新方法

@RequestMapping(value = "/addUser", method = {RequestMethod.POST}) 
public String addThisUser(@RequestBody String json) 
    { 
    String result = ""; 
    try 
    { 
     JSONObject jsonObject = new JSONObject(json); 
     result = addUser.addTheUser(jsonObject.getString("firstName"), 
       jsonObject.getString("lastName"), jsonObject.getInt("age"), 
       jsonObject.getString("email"), jsonObject.getLong("phoneNumber"), 
       jsonObject.getString("username"), jsonObject.getString("password")); 
    } 
    catch(JSONException exception) 
    { 
     result = "Something went wrong. Try again later"; 
    } 
    return result; 
    } 

然後我嘗試使用JdbcTemplate將值插入到表中。然而,它不工作,我不明白爲什麼。這裏是(我得到一個DataAccessException的)代碼:

dbConnecter.update("INSERT INTO userInformation (firstName, lastName, age, email, phoneNumber, username, password) " 
      +"VALUES (?, ?, ?, ?, ?, ?, ?)", 
      new Object[] {thisFirstName, thisLastName, thisAge, thisEmail, thisPhoneNumber, thisUsername, thisPassword}); 
    catch(DataAccessException exception) 
    { 
     output = "Cannot access database"; 
     exception.printStackTrace(); 
    } 

    catch(Exception exception) 
    { 
     output = "Unknown error"; 
     exception.printStackTrace(); 
    } 

我也想指出的是,select語句正常工作:

String queryString = "SELECT * FROM userInformation"; 


    List<Map<String, Object>> listOfUsers = dbConnecter.queryForList(queryString); 

老實說,我不知道爲什麼會這樣。有人可以幫忙嗎?

+1

你有沒有例外stracktrace?如果是,請提供。 – davidxxx

+0

顯示的錯誤是什麼? –

+0

什麼不起作用? –

回答

2

一個明確的錯誤信息將有助於提供更好的答案。但如果需要,請嘗試以下操作:

Statement statement = dbConnection.createStatement(); 
statement.executeUpdate(updateTableSQL); 
+0

我使用了PreparedStatement接口,它工作!非常感謝你 – Maths2468

+0

@ Maths2468很高興你發現它有幫助 –