Beroo
Beroo

Reputation: 29

using ResultSet when row value from database is NULL

When querying the database directly, result is NULL, now Im using ResultSet to check if result is NULL, do something else, if result is not NULL, print the result: This my COde:

if(rs4 != null) {
            while(rs4.next()) {
            String ad =rs4.getString("number");                    
            System.out.println(ad);
            }
        }
        else{
            System.out.println("ZERO ENTRIES");
        }` 

Database row value is NULL,since there is no row returned from my query so definitely i expect the else statement to run, but now the if statement is still being excecuted and prints null

Upvotes: 0

Views: 1753

Answers (3)

Beroo
Beroo

Reputation: 29

I finally found a way to go around it. Using rs.getInt() this will return 0 whenever row value is NULL and return new row value , whenever there is a row found.

This solved it :-)

while(rs.next())
        {
            // using rs.getInt() will return zero when row value from your query is NULL
            int i = rs.getInt("number");
            if(i<0) //check if zero
            {
                // When result is NULL i =0
                System.out.println("your value");
            }else{
                //When there are rows found from database i > 0
                String ad=rs.getString("number");
                System.out.println(ad);
            }
        }`

Upvotes: 0

dcalap
dcalap

Reputation: 1072

You can use something like:

if (!resultSet.isBeforeFirst() ) {    
    System.out.println("No data"); 
} 

Or:

if (!resultSet.next() ) {
    System.out.println("no data");
} 

Upvotes: 0

alayor
alayor

Reputation: 5035

What you see as NULL when querying the DB directly is the value of the column number, not the value of the row.

so, that's why you get a non-null row with a NULL value in number column in your ResultSet.

Upvotes: 1

Related Questions