2012-08-29 77 views
1

我獲得以下錯誤,但我不明白爲什麼:嵌套的異常是java.sql.SQLException中:無效的參數指標1

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback;錯誤的SQL語法[UPDATE da_tracking SET ins_name = xyz,ins_dev_scripted = False WHERE ins_ID = 12];嵌套0​​例外是值java.sql.SQLException:無效的參數指標1.

------------------------ dao class----- 
public int save(DboBean record) { 
     // TODO Auto-generated method stub 
     String sql = "UPDATE da_tracking" 
        + " SET ins_name= " + record.getDboDevName()+ "," 
        + " ins_dev_scripted = " + record.getDevScripted() 
        + " WHERE ins_ID = " + record.getDboId(); 
     Object[] params = new Object[] {record.getDboDevName(), record.getDevScripted()}; 
     int[] types = new int[]{Types.VARCHAR, Types.BIT}; 
     return jdbcTemplate.update(sql, params, types); 
    } 
----------------------------Junit----- 
bean.setDboDevName("xyz"); 
bean.setDboId(12); 
int rowsAffected = objDao.save(bean); 

    System.out.println("Object is updated [" + bean.getDboId() + ", " + bean.getDboDevName() + 
      ", " + bean.getDevScripted() + "]"); 

你知道爲什麼? 我的刪除&閱讀方法的工作。

回答

1
public int save(DboBean record) { 

     String sql = "UPDATE da_tracking" 
        + " SET ins_name= ?"+"," 
        + " ins_dev_scripted = ?" 
        + " WHERE ins_ID = ?"; 
     Object[] params = new Object[] {record.getDboDevName(), record.getDevScripted(), record.getDboId()}; 
     int[] types = new int[]{Types.VARCHAR, Types.BIT, Types.INTEGER}; // Change 3rd parameter type here 
     return jdbcTemplate.update(sql, params, types); 
    } 

----------------------------Junit----- 
bean.setDboDevName("xyz"); 
bean.setDboId(12); 
int rowsAffected = objDao.save(bean); 

    System.out.println("Object is updated [" + bean.getDboId() + ", " + bean.getDboDevName() + 
      ", " + bean.getDevScripted() + "]"); 

這是行嗎?

+0

您應該使用綁定變量(參數化查詢)是正確的,但這不是此錯誤的來源。你是對的,變量(可能只有'ins_name')需要被引用,但是SQL解析器還沒有得到那麼深的解析查詢。 –

+0

更新了代碼。請立即檢查。 – Garbage

+0

是的,它的工作原理:-D Thx – user1631032

4

您所看到的錯誤是因爲你傳遞變量到paramstypes陣列,但是你有沒有把那些綁定變量佔位符在查詢:

String sql = "UPDATE da_tracking" 
      + " SET ins_name= ?," 
      + " ins_dev_scripted = ?" 
      + " WHERE ins_ID = ?" 
Object[] params = new Object[] {record.getDboDevName(), record.getDevScripted(), record.getDboId()}; 
int[] types = new int[]{Types.VARCHAR, Types.BIT, Types.INTEGER}; 
return jdbcTemplate.update(sql, params, types); 

內部,春天是做像這樣:

PreparedStatement stmt = conn.prepareStatement("...your sql..."); 
stmt.setString(1, dboDevName); // this will fail, since there is no bind variable 
           // with index 1 
... 

你應該永遠不要通過連接外部數據建立SQL查詢。在最好的情況下,如果有人在數據中添加了奇怪的引用或轉義字符,並且最糟糕的情況下會導致系統崩潰,那麼這將導致查詢失敗。

+0

就是這樣。它的工作原理:D謝謝 – user1631032

相關問題