PreparedStatement抛出语法错误
我正在使用PreparedStatements准备一个查询,当我用条件参数硬编码查询时它运行正常。
如果参数是从setString()方法传递的,则抛出错误。
com.mysql.jdbc.JDBC4PreparedStatement@2cf63e26: select * from linkedin_page_mess ages where company_id = '2414183' com.mysql.jdbc.exceptions.jdbc4.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 '?' at line 1
在错误日志中,我的查询上面看起来很好。
public JSONObject getLinkedInMessages(String compId) { linlogger.log(Level.INFO, "Called getLinkedInMessages method"); Connection conn = null; Statement stmt = null; ResultSet rs = null; JSONObject resObj = new JSONObject(); JSONArray tempArray = new JSONArray(); try { conn = InitOrGetConnection(); String query = "select * from linkedin_page_messages where company_id = ?"; PreparedStatement pst=conn.prepareStatement(query); pst.setString(1, compId); System.out.println("\n\n"+pst.toString()); rs= pst.executeQuery(query); // process resultset logics } catch(Exception e) { System.out.println(e); linlogger.log(Level.INFO, "Exception occured "+e.toString()); } }
PreparedStatements有什么问题吗?
删除此行中的参数:
rs= pst.executeQuery(query);
一定是
rs= pst.executeQuery();
因为该语句是在PreparedStatement pst=conn.prepareStatement(query);
execute(String sql)
inheritance自Statement并将执行satement(sql)而不做好准备。
从中删除参数
rs= pst.executeQuery(query);
改成
rs= pst.executeQuery();
如果你在pst.executeQuery(query);
传递查询pst.executeQuery(query);
作为参数,此传递的query
字符串优先于您在conn.prepareStatement(query);
传递的query
字符串conn.prepareStatement(query);
并且因为在query
( select * from linkedin_page_messages where company_id = ?
)你dint传递参数你得到错误。