0

I have following code in one of my JSPs.

<% if(rsmatches!=null){%>
              <table>
                  <tr>
                      <td class="captions">Match</td>
                      <td>

                          <select>
                              <%

                               while(rsmatches.next()){ 
                                %>
                                <option value="<%out.print(rsmatches.getString("matchid"));%>"><%out.print(rsmatches.getString("matchid"));%> - <%out.print(rsmatches.getString("team1name"));%> vs <%out.print(rsmatches.getString("team2name"));%></option>
                                <%}%>
                          </select>
                      </td>
                  </tr>
              </table>

              <%} else{%>
              <h1>No Result</h1>
              <%}%>

So rsmatches is the resultset and when it is not null it gives the output as I expected, but when the Resultset has no results, Instead of showing

No Result

, It shows the dropdown with no values in it. Where did I do the mistake?

4

4 回答 4

3

have you tried this

<% if(rsmatches!=null && rsmatches.next()){%>
<table>
    <tr>
        <td class="captions">Match</td>
        <td>

        <select>
        <%

            do{ //Change to do while since result set is already pointing to the first row coz of the statement in if loop
        %>
                <option value="<%out.print(rsmatches.getString("matchid"));%>"><%out.print(rsmatches.getString("matchid"));%> - <%out.print(rsmatches.getString("team1name"));%> vs <%out.print(rsmatches.getString("team2name"));%></option>
            <%} while(rsmatches.next()) ;%>
        </select>
        </td>
    </tr>
</table>
<%} else{%>
<h1>No Result</h1>
<%}%>
于 2013-10-13T18:49:30.013 回答
1

Try this:

<% if( rsmatches != null && rsmatches.size() > 0 ) { %>
于 2013-10-13T18:35:18.587 回答
0

Sounds like rsmatches is empty (instantiated) not null which would explain why the else does not fire.

于 2013-10-13T18:36:29.817 回答
0

You are doing it in wrong way. Ideally, you shouldn't have database related code inside, the JSP that shows the poor design of the application and violation of application layers.

Now to answer your question, ResultSet will never be null, even if there is no record fetched using query. Ideally, you should handle this scenario using

  1. Read resultset in some class (preferably DAO) and then build a collection. Later pass this collection to JSP to display data.

  2. Along with checking null, fire resultSet.next() method to determine if next record exists. Later instead of using while loop use Do... while loop.

于 2013-10-13T18:44:34.330 回答