調試時發現每次執行到 while(rs.next()) 就跳入異常塊,錯誤信息:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 '? and t.colpas=?' at line 1
ResultSet rs = ps.executeQuery(sql); // sql 仍包含佔位符 ?
PreparedStatement.executeQuery() 不接受 SQL 字符串參數。調用帶參重載時,驅動會嘗試再次解析含 ? 的 SQL,導致語法錯誤。正確做法是先 ps.setXxx(...) 綁定參數,再調用無參的 executeQuery()。
ps.setString(1, param1);
ps.setString(2, param2);
ResultSet rs = ps.executeQuery(); // 無參版本
修改後即可正常查詢並遍歷結果集。