2015-04-28 158 views
0

在使用PreparedStatements準備查詢時,它運行正常,當我用條件參數硬編碼查詢時。PreparedStatement引發語法錯誤

但會拋出錯誤,如果參數是從setString()方法傳遞的。

[email protected]: 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有什麼問題嗎?

+1

看着錯誤信息,'linkedin_page_mess ages'中似乎有一個空格 –

+0

不存在.. – user4771244

回答

1

刪除參數這一行:

rs= pst.executeQuery(query); 

它必須是

rs= pst.executeQuery(); 

由於聲明在PreparedStatement pst=conn.prepareStatement(query);

execute(String sql)準備從Statement繼承和將執行的語句( SQL)沒有準備好它。

+0

在'PreparedStatement'上,'execute(String)'**必須拋出一個異常(參見javadoc),但是它只是偶然地在MySQL上這樣做。 –

2

rs= pst.executeQuery(query); 

變化

rs= pst.executeQuery(); 

如果您在pst.executeQuery(query);傳遞查詢作爲參數,那麼這個傳遞query串優先於你conn.prepareStatement(query);,自傳入的query string取消參數queryselect * from linkedin_page_messages where company_id = ?)你dint傳遞參數,你會得到錯誤。