表是空的还是没有

时间:2012-06-02 05:57:46

标签: java

Statement st=null;
ResultSet rs=null;
Connection con=null;

String sql="select * from employee;";

try{

                con= new Database().getMySqlConnection();
                st=con.prepareStatement(sql);
                rs=st.executeQuery(sql);

    while(rs.next())
    {
if(rs.getInt("id")!=-1)     
{
  %>
 <tr><td align="center"><%=rs.getInt("id")%></td> 
 <td align="center"><%=rs.getString("name")%></td>
  <td align="center"><%=rs.getInt("salary")%> </td>
   <td align="center"><%=rs.getString("Designation") %></td>
}
    else
    {

        out.println("table is empty");
    } 
    }   
  }


                catch (SQLException ex) {
                    System.out.println(ex.getMessage());
                }

在这个程序中,我想在页面上显示数据,通过从表中检索是否为空,如果表为空则显示消息或打印该表为空。但它无法显示任何消息,当表中的数据正常工作时 但是当表为空时,不会显示错误消息。

我在网上看到很多例子,执行wasNull()方法,islast(),iffirst()方法等,但仍然存在问题。

Plz建议解决方案。这个程序在java。

2 个答案:

答案 0 :(得分:3)

你的空表语句应该在while语句之外。使用旗帜。

while(rs.next())
{
    flag = 1;
    if(rs.getInt("id")!=-1)     
       {
        <tr><td align="center"><%=rs.getInt("id")%></td> 
        <td align="center"><%=rs.getString("name")%></td>
        <td align="center"><%=rs.getInt("salary")%> </td>
        <td align="center"><%=rs.getString("Designation") %></td>
       }
}   
if ( flag == 0 )
     out.println("Table is empty");

next() method一直向前移动光标一行。如果输入while循环,则表示表格中有内容。

答案 1 :(得分:2)

您的消息在while循环中。如果表中没有数据,则rs.next将返回false。 你必须在循环之外移动msg。

你可以使用其值改变的boolean var,同时查找是否返回了任何数据,或者你可以使用if-else&amp;的组合。做-而

 if(rs.next()){
     do{
        //process data
       }while(rs/next);
 }else{
     //Print MSG
 }