简体   繁体   中英

how to check database table is empty or not

i have a database with a table 'admin'.But presently just creating table not having any values.table columns are user_name and password.My motive is to check whether the table is empty or not.I am using mysql database.I tried following code and its fails.Please help me.

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);
    }
}

If you just need to check the table then you should use query:

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

for better performance. And get the row count from ResultSet to check the table is null or not.

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

Try this code, I think this will do it. I updated it coz the first I post here is not working at all, my bad.

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);
        }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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