2015-12-10 123 views
1

我試圖發送得到的城市餐館是拉合爾,Rwp等(用戶將輸入表格中的內容 但我沒有收到任何東西 如果我在查詢中硬編碼和輸入城市名稱,然後自己它的工作原理否則不返回任何東西。 同樣的問題我有太多,當我嘗試添加任何東西。在mysql中插入變量

基本上我需要在MySQL查詢使用變量的幫助。

什麼我做錯了嗎?

public ResultSet getRestaurants(String city){ 
    Statement statement; 
    try { 
     statement = con.createStatement(); 
     String query = "select * from restaurantinfo WHERE city = '"+city+"'"; 
     ResultSet rs = statement.executeQuery(query); 
     return rs; 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return null; 
    }  
} 

這是處理結果集。我知道有錯誤。我會解決它們。我關心的是顯示了餐廳..

<% 
 
\t DbConnection dbc = new DbConnection(); 
 
\t String city = request.getParameter("city"); 
 
\t ResultSet rs = dbc.getRestaurants(city); 
 
\t 
 

 
\t %> 
 
     <% 
 
     while(rs.next()){ 
 
\t \t %> 
 
\t <section class="main-wrap"> 
 
    \t <section class="sidebar"> 
 
    \t \t \t <form id="filtercousine"> 
 
       <div ><br> 
 
\t \t \t \t <h4 style="margin-bottom:-5px;"> Filter by Cuisines</h4><br> 
 
       <input id="fastfood" type="checkbox" style="" name="fastfood" value="fastfood">Fast Food <br/> 
 
       <input id="pakistani" type="checkbox" name="gender" value="Pakistani">Pakistani <br/> 
 
       </div> 
 
      </form> 
 
     </section> 
 

 
\t \t <section class="content-wrap"> 
 
     \t <ul> 
 
      \t <li> <input type="submit" id="menu" value="Go to Menu" class="main-button" style="float:right; margin-right:6px;"><h3><%= rs.getString("name") %></h3></li> 
 
      \t <li style="font-style:italic; margin:-15px 0 5px 0;"> <%= rs.getString("cousines") %></li> 
 
      \t <li style="color:#999; margin-bottom:2px;"> Delivery:</li> 
 
      \t <li >Free</li> 
 
      </ul> \t 
 
     </section> 
 
    </section> 
 
    <% \t \t 
 
\t } \t 
 
\t %>

這是我的數據庫中的圖片 View

+0

一般來說,看起來不錯。城市是否有任何前/後空白?在運行它之前可以幫助打印查詢,並確切地查看它的樣子。 – DBug

+0

我已添加處理結果集的代碼.. 我編輯了該職位 –

回答

1

第一關 - 這似乎很奇怪,你沿着ResultSet中穿過的直接處理,而不是那。還請分享代碼處理 ResultSet - 可能錯誤在那部分。

對於你的方法:使用PreparedStatement而不是請考慮此變體:

public ResultSet getRestaurants(String city){ 
    try { 
     System.out.println("CITY: " + city); 
     PreparedStatement ps = con.prepareStatement(
      "select * from restaurantinfo WHERE city = ?"); 
     //Set first ? with value of city 
     ps.setString(1, city); 
     //return resultset 
     return statement.executeQuery(query); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
     return null; 
    }  
} 
+0

我沒有實際使用過Prepared Statement .. –

+0

我已經添加了處理結果集的代碼.. 我已編輯帖子 –

+0

如果說「城市」參數其實是一個字符串?你從一個組合框(