Elio  Rahy
Elio Rahy

Reputation: 43

How to check if ResultSet is empty?

I am trying to launch a class only if a select query returned at least a row.

My call to thequery function noted below:

results=thequery("SELECT `username`,`numberpoints` FROM `highscores` WHERE `username` = '"+name+"'");//send query that checks if username exist     
                if(!results.next()) {
                BallTrial trial = new BallTrial();
                }

thequery function:

public ResultSet  thequery(String query){

         PreparedStatement statement = null;
        ResultSet rs = null;

        Connection con=null;
        Statement st=null;
        try {
            con=DriverManager.getConnection("jdbc:mysql://localhost/scores","root","");

            statement = con.prepareStatement(query);

            rs=  statement.executeQuery();

            while(rs.next()){
                    System.out.println(rs.getString(1)+" "+rs.getString(2));

                    return rs;

            }}


        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("you have not accessed the data base");

        }

        return null;

    }

I am getting a null pointer exception at if(!results.next()) {, can anyone clarify what is my mistake here?

Upvotes: 0

Views: 987

Answers (3)

J.Srivastava
J.Srivastava

Reputation: 51

while(true) {
            if (!results.next()){
               System.out.prinln("result has no data");
            }else{               
                  System.out.prinln("result has some data");
            }
        }

Upvotes: 0

Govinda Sakhare
Govinda Sakhare

Reputation: 5729

You should add the null check condition before calling next, the condition needs to be tweaked something around the lines: results != null && !results.next()

Upvotes: 1

Darshan Mehta
Darshan Mehta

Reputation: 30809

You need to make a couple of changes:

  1. From thequery method, return ResultSet (i.e. rs) instead of returning null. Returning null will cause NPE. Also, remove while(...) as it needs to be done by the caller, e.g.

    public ResultSet  thequery(String query){
    
     PreparedStatement statement = null;
     ResultSet rs = null;
    
     Connection con=null;
     Statement st=null;
     try {
         con=DriverManager.getConnection("jdbc:mysql://localhost/scores","root","");
         statement = con.prepareStatement(query);
         rs=  statement.executeQuery();
         return rs;
     catch (SQLException e) {
         e.printStackTrace();
         System.out.println("you have not accessed the data base");
         throw e;
     }
    }
    
  2. In the caller method, check whether ResultSet contains any records by calling rs.next(), e.g.:

    results = thequery(..)
    if(!results.next()){
        BallTrial trial = new BallTrial();
    }
    

Upvotes: 1

Related Questions