1. 程式人生 > >使用PreparedStatement,出現You have an error in your SQL syntax; check the manual that corresponds to you

使用PreparedStatement,出現You have an error in your SQL syntax; check the manual that corresponds to you

PreparedStatement時,出現了錯誤: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 mstate=?’ at line 1。而且sql語句的佔位符與為其賦值的setXXX方法相匹配,並沒有錯。
經排查,是獲得結果集時,多寫了引數。ResultSet rSet = pps.executeQuery(sql);
與Statement不同,在建立PreparedStatement時,便為其指定了sql語句,獲得結果集時不需要再指定了。而Statement建立時未指定,獲得結果集時需要制定。
建立 PreparedStatement 與執行sql語句:

PreparedStatement pps = con.prepareStatement(sql);
ResultSet rSet = pps.executeQuery();

建立 Statement與執行sql語句:


Statement statment = con.createStatement();
ResultSet rSet = statment.executeQuery(sql);

另外,在使用PreparedStatement時,需要為sql語句中每一個佔位符通過setxxx方法賦值,並且其值不能為空。不然會查詢不到內容。