2012-10-22 28 views
0
public ArrayList<Message> searchMessages(String word) throws DaoException{ 
    ArrayList<Message> messages = new ArrayList<>(); 
      Connection con = null; 
    PreparedStatement ps = null; 
    ResultSet rs = null; 

    try { 
     con = getConnection(); 

     //String query = "SELECT * FROM messages WHERE text LIKE %?% order by date"; 
     String query = "SELECT * FROM messages WHERE text LIKE '%?%'"; 
     ps = con.prepareStatement(query); 
     ps.setString(1,word); 
     rs = ps.executeQuery(); 

     while (rs.next()) { 
      int messageId = rs.getInt("messageId"); 
      String text = rs.getString("text"); 

      String date = rs.getString("date"); 
      int memberId2 = rs.getInt("memberId"); 
      Message m = new Message(messageId,text,date,memberId2); 
      messages.add(m); 

      //Company c = new Company(companyId, symbol, companyName, sharePrice, high, low); 
      //companies.add(c); 
     } 
    } catch (SQLException e) { 
     throw new DaoException("searchMessages(): " + e.getMessage()); 
    } finally { 
     try { 
      if (rs != null) { 
       rs.close(); 
      } 
      if (ps != null) { 
       ps.close(); 
      } 
      if (con != null) { 
       freeConnection(con); 
      } 
     } catch (SQLException e) { 
      throw new DaoException("searchMessages(): " + e.getMessage()); 
     } 
    } 

    return messages; 

} 

只是解釋代碼有點first.It只是簡單地搜索信息表,其無論是supplied.I用事先準備好的聲明中插入文本字段它進入查詢和物質運行it.No我提供什麼字符串它給這個錯誤當注射到一個SQL查詢使用Java,會得到一個錯誤

oow_package.DaoException: searchMessages(): Parameter index out of range (1 > number of parameters, which is 0). 

不知道爲什麼它沒有絲毫的工作。將不勝感激任何幫助。

+0

如果您找到了正確答案,請檢查旁邊的代碼,將其標記爲已接受的答案。 – Alfabravo

回答

5

您不能在準備好的語句中使用這樣的參數。查詢應該是

SELECT * FROM messages WHERE text LIKE ? 

而且你應該使用

ps.setString(1, "%" + word + "%"); 
+0

這是正確的,它修復它非常感謝。現在更新帖子,並將它標記爲正確的答案,當它允許我。謝謝很多 – Daniel

0

我不是專家,但我要說你準備好的語句不帶參數的認可,你仍然插入一個(字) ...也許麻煩來自%符號?

編輯:同意上面的人......看起來合法。

相關問題