2

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.jspand 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.

Simon M.
  • 2,244
  • 3
  • 17
  • 34

3 Answers3

5

jeuResultats.next(); moves your result to the next row. You start with 0th row, i.e. 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 e.x., 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
dubes
  • 5,324
  • 3
  • 34
  • 47
1

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);
}
Vivek Singh
  • 2,047
  • 11
  • 24
0

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();
}
Vivek Singh
  • 2,047
  • 11
  • 24
Bhuwan Prasad Upadhyay
  • 2,916
  • 1
  • 29
  • 33