在開發過程中,一個經典的低級錯誤是構建了查詢條件卻忘記傳遞給執行方法。這篇文章通過一個真實的 `getList` 方法案例,展示了這類問題的成因與修復。
原始代碼中,開發者根據參數 `xh`(學號)動態拼接了 `where` 子句,但在調用 `findAll` 時卻傳入了空字串 `""`,導致條件失效,查詢返回全表數據。
public List getList(int xh) {
String where = "";
if (xh != 0) {
where = where + " where xuehao=" + xh + "";
}
// 錯誤點:這裡傳入了空字串,而非構建好的 where 條件
return this.findAll("");
}
只需將 `findAll` 的參數改為變量 `where` 即可:
public List getList(int xh) {
String where = "";
if (xh != 0) {
where = where + " where xuehao=" + xh + "";
}
// 修正:傳入構建好的條件
return this.findAll(where);
}
雖然上述修正解決了邏輯錯誤,但字串拼接 SQL 存在嚴重的 SQL 注入 風險。生產環境中強烈建議使用 參數化查詢 或 ORM 框架(如 MyBatis、Hibernate)的條件構建器:
// 使用 MyBatis 範例
這樣既安全又優雅,能從根本上杜絕拼接錯誤與注入漏洞。