繁体   English   中英

如何检查数据库表是否为空

[英]how to check database table is empty or not

我有一个带有表“admin”的数据库。但目前只是创建没有任何值的表。表列是用户名和密码。我的动机是检查表是否为空。我正在使用 mysql 数据库。我尝试以下代码和它的失败。请帮助我。

public void nullCheck() {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    String qry = "SELECT * From admin ";

    try {
        stmt = (PreparedStatement) conn.prepareStatement(qry);
        rs =  stmt.executeQuery();

        boolean empty = true;
        while( rs.next() ) {
          // ResultSet processing here
          empty = false;
        }
        if( empty ) {
            Util.showWarningMessageDialog("null");
        }
    } catch (SQLException ex) {
        Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
    }
}

如果您只需要检查表,那么您应该使用查询:

String qry = "SELECT count(*) From admin ";

以获得更好的性能。 并从 ResultSet 获取行数以检查表是否为空。

int count=0;
while( rs.next() ) 
{
    count=rs.getInt("count");
}

试试这个代码,我认为这会做到。 我更新了它,因为我在这里发布的第一个帖子根本不起作用,我的错。

public void nullCheck() {

       PreparedStatement stmt = null;
       ResultSet rs = null;
       String qry = "SELECT * From admin ";

       try {
            stmt = (PreparedStatement) conn.prepareStatement(qry);
            rs =  stmt.executeQuery();
            int count = 0;
            while(rs.next()){
               count++;
            }
            if(count == 0){ // if equal to 0 then the table is null
               bla bla bla
            }
       } catch (SQLException ex) {
               Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
        }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM