1

I have the following code to get and return records count from the database and assign it into the object.

rs = stmt.executeQuery( "SELECT COUNT(*) FROM TEST" );

I have the following code to check whether records is found:

    if (rs.next() && rs.getString( 1 ).equals( "1" )) {
        logger.info( "DID Find Records !!! " );
    } else {
        logger.info( "DID NOT Find Records !!! " );
    }

How can I check return records is more then 0 in this case?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • why don't you do `if (rs.next() && rs.getInt(1) > 0 ))` instead of `if (rs.next() && rs.getString( 1 ).equals( "1" ))`? or did I misunderstand your question? – Kartik Aug 28 '18 at 01:31
  • looks like just `if (rs.next())` is fine. refer: https://stackoverflow.com/questions/867194/java-resultset-how-to-check-if-there-are-any-results – Troy Young Aug 28 '18 at 01:39

4 Answers4

1

Replace

if (rs.next() && rs.getString( 1 ).equals( "1" ))

by

if (rs.next() && rs.getInt(1) > 0))

Kartik
  • 7,677
  • 4
  • 28
  • 50
0

You will need to use an alias, then extract the returned count from rs as an integer, simply change your code to this:

  rs = stmt.executeQuery( "SELECT COUNT(*) FROM TEST AS TESTCOUNT" );
  rs.next();
  if (rs.getInt("TESTCOUNT") > 0) {
    logger.info( "DID Find Records !!! " );
  } else {
    logger.info( "DID NOT Find Records !!! " );
  }

where 'TESTCOUNT' is the alias name given.

SagarScript
  • 1,145
  • 11
  • 15
0

rs.getString( 1 ) contains value of row count from database. Just parse it to Integer to the number of rows

 if (rs!=null && rs.next()) {
        logger.info( "DID Find Records !!! " );
        logger.info( "RowCount "+ Integer.valueOf(rs.getString( 1 )));
    } else {
        logger.info( "DID NOT Find Records !!! " );
    }
sc1234
  • 23
  • 1
  • 4
0

Make it to a int variable and do the checks...!

ResultSet rs = .....;

int count = -1;

if (rs.next())
    count = rs.getInt(1);

if (count <= 0)
{
    logger.info("no records");
}
else if (count == 1)
{
    logger.info("found 1 record");
}
else
{
    logger.info("found more...");
}bb
K Adithyan
  • 386
  • 4
  • 12