如何检查结果集是否为空

时间:2014-03-10 13:20:32

标签: jsp

我有一个结果集。如果结果集为空或为null,那么我想在str16中设置“int b = 0”的值。如果结果集不为空/找不到内容,则执行查询。但是当结果集为空时我遇到了一些问题,那么在str16中没有设置值。我在我的项目中所做的是,在登录后,如果他已经休假,我将显示员工资料的总休假数。如果员工没有休假,则在个人资料中显示0。

checkleave.jsp

     <%@ page import="java.sql.*" %> 
    <%@ page import="java.io.*" %> 
     <%
       // storing the login id in abc becouse i have give table name as employee id 
      String abc= session.getAttribute("empid").toString();
      %>
      <%    
        try{
     int b=0;         
            Statement st=connection.createStatement();  

     ResultSet rs=st.executeQuery("select approcode,approemail,appromon,approvemon,approtue,approvetue,approwed,approvewed,approthr,approvethr,approfri,approvefri,approsat,approvesat,commen,months,SUM(nol) from `pushkalit`.`approval`WHERE (CONVERT( `approcode` USING utf8 ) LIKE '%"+abc+"%')");// here what i am doing  that if employee login then check in approval table where is approcode column as employee id if find something then execute table if column is not there then put value of b(i have declared int b=0) in str16. 

   if(rs !=null)       
   {  
     if (rs.isBeforeFirst() && rs.isAfterLast())  
      {  
       session.setAttribute("str16",b);
        }
        else
       {       
         while(rs.next())
        {  
          String str=rs.getString("approcode");
          String str1= rs.getString("approemail");
          String str2=rs.getString("appromon");
            String str3=rs.getString("approvemon");
          String str4=rs.getString("approtue"); 
          String str5=rs.getString("approvetue");
           String str6=rs.getString("approwed"); 
              String str7=rs.getString("approvewed");
              String str8=rs.getString("approthr");
              String str9=rs.getString("approvethr");
               String str10=rs.getString("approfri");
              String str11=rs.getString("approvefri");
            String str12=rs.getString("approsat");
           String str13=rs.getString("approvesat");
              String str14=rs.getString("commen");
             String str15=rs.getString("months");
             String str16=rs.getString(17);
            session.setAttribute("str16",str16);    
        }      
    }
    }
    else
    {
    session.setAttribute("str16",b);
    }

}
catch(Exception e) {
    System.out.println(e);
}
 %>

但是当员工登录时我遇到问题,如果列为空则会出错。 这是empprofile.jsp.it将在登录后到来。这个代码我已经放入empprofile.jsp

<%
  String a = session.getAttribute("str16").toString();
 int y = Integer.parseInt(a);
 <tr><td><label>Total Leave Day:</label></td>
    <td><%=y %></td>
  %>

1 个答案:

答案 0 :(得分:0)

如果rs.next()==false,结果集为空。所以在你的情况下,做一个布尔值,在while(rs.next())循环中设置它,并在循环后检查。

boolean blnResultSetIsEmpty = true;
while(rs.next())
{
   blnResultSetIsEmpty = false;
   ...
}
if(blnResultSetIsEmpty)
{
   out.print("There were no results");
}

或者,因为你的代码显然只期望一行,所以使用if语句而不是while循环:

if(rs.next())
{
   ...
}
else
{
   out.print("There were no results");
}