简体   繁体   中英

Why my query result returns me false

I'm new with java and sql query and for the user connexion, I connect to the DB and check if the login exists. Here is what I do :

requete = "SELECT Login,Password,DroitModifAnnuaire,DroitRecepteurDem,DroitResponsableDem,PiloteIso,Administrateur,DroitNews,DroitTenues,DroitEssai,Nom,Prenom  FROM Annuaire WHERE Login='"
            + (request.getParameter("login") + "'");
instruction = connexion.createStatement();
jeuResultats = instruction.executeQuery(requete);
try{            
    jeuResultats.next();
} catch (SQLException e) {
    e.printStackTrace();
}
if (jeuResultats.next() == false) {
   loadJSP("/index.jsp", request, reponse);
}else {
    loadJSP("/views/menu.jsp", request, reponse);
}

The login that I enter is good but it redirect me to index.jsp and I have the error : the result set has no current row

I tried to search answer to this error but I didn't found. So why it returns me false ? While when I do System.out.println(jeuResultats.getString(1)); the login is printed.

jeuResultats.next(); moves your result to the next row. You start with 0th row, ie when you call .next() it reads the first row, then when you call it again, it tries to read the 2nd row, which does not exist.

Some additional hints, not directly related to the question:

  1. Java Docs are a good place to start Java 8 ResultSet , for ex, perhaps ResultSet.first() method may be more suited for your use.
  2. Since you are working with resources, take a look at try-with-resources syntax. Official tutorials are a good starting point for that.
  3. Also take a look at prepared statement vs Statement. Again, official guide is a good place to start

Make the below changes in you code. Currently the next() method is shifting result list to fetch the data at 1st index, whereas the data is at the 0th Index:

boolean result = false;
try{            
    result = jeuResultats.next();
} catch (SQLException e) {
    e.printStackTrace();
}
if (!result) {
   loadJSP("/index.jsp", request, reponse);
}else {
    loadJSP("/views/menu.jsp", request, reponse);
}

Replace your code by below code:

requete = "SELECT Login, Password, DroitModifAnnuaire, DroitRecepteurDem, DroitResponsableDem, PiloteIso, Administrateur, DroitNews, DroitTenues, DroitEssai, Nom, Prenom  FROM Annuaire WHERE Login = '"
            + (request.getParameter("login") + "'");
instruction = connexion.createStatement();
jeuResultats = instruction.executeQuery(requete);

try{            
   if (jeuResultats.next()) {
      loadJSP("/index.jsp", request, reponse);
   } else {
      loadJSP("/views/menu.jsp", request, reponse);
   }
} catch (SQLException e) {
   e.printStackTrace();
}

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