简体   繁体   中英

Mysql Result set Error

I am executing a block of code where I need to retrieve a set of users from database and do some stuff with them. Very simple scenario. The problem is that although I use while(rs.next()) , when rs.next() reaches null my program tries to continue with the code inside while clause and exits with Null Exception.

Why is that happening? Is something broken in my code that I cannot figure out? Please, notice that rs is never null . At the beginning prints at the console all the contents of rs but when it reaches the end it returns null exception.

   try {                       
      String sql = "select distinct userid from userinfo";
      stmt1 = conn.createStatement();
      try (ResultSet rs = stmt1.executeQuery(sql)) {
         while (rs.next()) {
            String mentionsIDs = (rs.getString("mentions")).trim();

            try{
               if (!mentionsIDs.isEmpty() ){
                  System.out.println(mentionsIDs);
                  String[] arr = mentionsIDs.split("\\s+");
                  if(isNumeric(arr[0])){
                     System.out.println(arr[0]);
                     sources.add(Long.parseLong(arr[0]));
                  }
               }            
            }
            catch(Exception ex){
               Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            }
         }   
         rs.close();
      }

Any help is appreciated.

You must also check that the result set indeed have some results in it. Put a condition over your while loop which checks that rs is not null.

if(rs!=null) {
    while(rs.next()) {
        ... Process
    }
} else {
    System.out.println("The query returned 0 results");
}

In your code:

String sql = "select distinct userid from userinfo";
stmt1 = conn.createStatement();
try (ResultSet rs = stmt1.executeQuery(sql)) {
      if(rs!=null) {
      while (rs.next()){
      String mentionsIDs = (rs.getString("mentions")).trim();
      try{
          if (!mentionsIDs.isEmpty() ){
                System.out.println(mentionsIDs);
                String[] arr = mentionsIDs.split("\\s+");
                if(isNumeric(arr[0])){
                   System.out.println(arr[0]);
                   sources.add(Long.parseLong(arr[0]));
                }
          }
       }
       catch(Exception ex){
          Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
       }
   }   
   rs.close();
   }

Move String mentionsIDs = (rs.getString("mentions")).trim(); inside the try block then catch NullPointerException .

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