Why is “while (rs.next())” necessary here?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
29
down vote

favorite
1












I want to select the maximum line number from my database "Logs" and store it in a variable m.



Here's my code:



ResultSet rs = stmt.executeQuery("Select max(Line) as L from logs");

while (rs.next()) // Why do I need this
int m = rs.getInt("L");
System.out.println(m);



But it doesn't work unless I use while(rs.next()).




If I understand correctly, rs.next() moves the cursor to the next row, but here, in this result, I only have one row.



So, can someone explain why the loop is necessary? The only thing I can think of is that the first cursor is set on the column name, am I right?







share|improve this question






















  • You could just call it once, but you want to exhaust the result set just in case
    – Mike
    Aug 8 at 20:29






  • 14




    If you're only expecting one row, change it to if (rs.next()).
    – shmosel
    Aug 8 at 20:29






  • 3




    @shmosel or rs.next(); int m = rs.getInt("L");
    – YCF_L
    Aug 8 at 20:31







  • 6




    I'd code if (!rs.next()) throw new Exception("something is really out of shape here")
    – Moritz Both
    Aug 8 at 20:31






  • 2




    Related, possibly duplicate: stackoverflow.com/questions/49690750/…
    – Mark Rotteveel
    Aug 8 at 20:50














up vote
29
down vote

favorite
1












I want to select the maximum line number from my database "Logs" and store it in a variable m.



Here's my code:



ResultSet rs = stmt.executeQuery("Select max(Line) as L from logs");

while (rs.next()) // Why do I need this
int m = rs.getInt("L");
System.out.println(m);



But it doesn't work unless I use while(rs.next()).




If I understand correctly, rs.next() moves the cursor to the next row, but here, in this result, I only have one row.



So, can someone explain why the loop is necessary? The only thing I can think of is that the first cursor is set on the column name, am I right?







share|improve this question






















  • You could just call it once, but you want to exhaust the result set just in case
    – Mike
    Aug 8 at 20:29






  • 14




    If you're only expecting one row, change it to if (rs.next()).
    – shmosel
    Aug 8 at 20:29






  • 3




    @shmosel or rs.next(); int m = rs.getInt("L");
    – YCF_L
    Aug 8 at 20:31







  • 6




    I'd code if (!rs.next()) throw new Exception("something is really out of shape here")
    – Moritz Both
    Aug 8 at 20:31






  • 2




    Related, possibly duplicate: stackoverflow.com/questions/49690750/…
    – Mark Rotteveel
    Aug 8 at 20:50












up vote
29
down vote

favorite
1









up vote
29
down vote

favorite
1






1





I want to select the maximum line number from my database "Logs" and store it in a variable m.



Here's my code:



ResultSet rs = stmt.executeQuery("Select max(Line) as L from logs");

while (rs.next()) // Why do I need this
int m = rs.getInt("L");
System.out.println(m);



But it doesn't work unless I use while(rs.next()).




If I understand correctly, rs.next() moves the cursor to the next row, but here, in this result, I only have one row.



So, can someone explain why the loop is necessary? The only thing I can think of is that the first cursor is set on the column name, am I right?







share|improve this question














I want to select the maximum line number from my database "Logs" and store it in a variable m.



Here's my code:



ResultSet rs = stmt.executeQuery("Select max(Line) as L from logs");

while (rs.next()) // Why do I need this
int m = rs.getInt("L");
System.out.println(m);



But it doesn't work unless I use while(rs.next()).




If I understand correctly, rs.next() moves the cursor to the next row, but here, in this result, I only have one row.



So, can someone explain why the loop is necessary? The only thing I can think of is that the first cursor is set on the column name, am I right?









share|improve this question













share|improve this question




share|improve this question








edited Aug 8 at 20:42









Zabuza

10.5k52538




10.5k52538










asked Aug 8 at 20:26









JadedBeast

17726




17726











  • You could just call it once, but you want to exhaust the result set just in case
    – Mike
    Aug 8 at 20:29






  • 14




    If you're only expecting one row, change it to if (rs.next()).
    – shmosel
    Aug 8 at 20:29






  • 3




    @shmosel or rs.next(); int m = rs.getInt("L");
    – YCF_L
    Aug 8 at 20:31







  • 6




    I'd code if (!rs.next()) throw new Exception("something is really out of shape here")
    – Moritz Both
    Aug 8 at 20:31






  • 2




    Related, possibly duplicate: stackoverflow.com/questions/49690750/…
    – Mark Rotteveel
    Aug 8 at 20:50
















  • You could just call it once, but you want to exhaust the result set just in case
    – Mike
    Aug 8 at 20:29






  • 14




    If you're only expecting one row, change it to if (rs.next()).
    – shmosel
    Aug 8 at 20:29






  • 3




    @shmosel or rs.next(); int m = rs.getInt("L");
    – YCF_L
    Aug 8 at 20:31







  • 6




    I'd code if (!rs.next()) throw new Exception("something is really out of shape here")
    – Moritz Both
    Aug 8 at 20:31






  • 2




    Related, possibly duplicate: stackoverflow.com/questions/49690750/…
    – Mark Rotteveel
    Aug 8 at 20:50















You could just call it once, but you want to exhaust the result set just in case
– Mike
Aug 8 at 20:29




You could just call it once, but you want to exhaust the result set just in case
– Mike
Aug 8 at 20:29




14




14




If you're only expecting one row, change it to if (rs.next()).
– shmosel
Aug 8 at 20:29




If you're only expecting one row, change it to if (rs.next()).
– shmosel
Aug 8 at 20:29




3




3




@shmosel or rs.next(); int m = rs.getInt("L");
– YCF_L
Aug 8 at 20:31





@shmosel or rs.next(); int m = rs.getInt("L");
– YCF_L
Aug 8 at 20:31





6




6




I'd code if (!rs.next()) throw new Exception("something is really out of shape here")
– Moritz Both
Aug 8 at 20:31




I'd code if (!rs.next()) throw new Exception("something is really out of shape here")
– Moritz Both
Aug 8 at 20:31




2




2




Related, possibly duplicate: stackoverflow.com/questions/49690750/…
– Mark Rotteveel
Aug 8 at 20:50




Related, possibly duplicate: stackoverflow.com/questions/49690750/…
– Mark Rotteveel
Aug 8 at 20:50












5 Answers
5






active

oldest

votes

















up vote
69
down vote



accepted










Why?



The cursor is initially placed before the first element. You need to advance it once to access the first element.



This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:




Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.





Solution



So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:



rs.next();
// Access the result


However, you probably want to account for the case where there was no match at all, since:




When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.




So the code would fail in this case.



Because of that, you should account for the case and use the returned boolean to guard your access:



if (rs.next()) 
// Access result ...
else
// No match ...






share|improve this answer


















  • 9




    A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
    – Andreas
    Aug 8 at 21:24






  • 3




    To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
    – Barranka
    Aug 9 at 12:20







  • 3




    @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
    – Lightness Races in Orbit
    Aug 9 at 12:41


















up vote
20
down vote













From the official documentation (which you should have read btw):




Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.




You basically need to move it, in your case moving it once is enough:



 rs.next(); 
System.out.println(rs.getInt("L"));





share|improve this answer





























    up vote
    9
    down vote













    You can convert this to use a simple if statement instead.



    if(rs.next()) 
    // other code here



    You would use while when you have more than one row to bring back.






    share|improve this answer
















    • 2




      No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
      – YCF_L
      Aug 8 at 20:33






    • 6




      @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
      – Mark Rotteveel
      Aug 8 at 20:37







    • 2




      @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
      – Mark Rotteveel
      Aug 8 at 20:42

















    up vote
    8
    down vote














    A ResultSet cursor is initially positioned before the first row, the
    first call to the method next makes the first row the current row, the
    second call makes the second row the current row, and so on.




    consider you have something like this.



    ->1->2->3
    ^


    your "rs" is initially pointed before 1, when you call rs.next() it advances the arrow to point to 1



     ->1->2->3
    ^


    so if you do not call the next() method then you do not get the result.



    Hope this helps






    share|improve this answer





























      up vote
      1
      down vote













      There are different types of Executing the Commands. Cursors are used to read the data from your executed queries. When you execute to Read, you using Forward Only Cursor by default hence you are only getting next result after calling Recorset.Next() ! I don't want to go in much deeper here. You can read about cursors here : https://docs.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado?view=sql-server-2017



      The best solution in your case is to use Scalar Resultset which will return only ONE CELL thats exactly what you want to implement without having to loop through your result set. Following example shows how you can implement such :



      using System;
      using System.Data;
      using System.Data.SqlClient;

      class ExecuteScalar

      public static void Main()

      SqlConnection mySqlConnection =new SqlConnection("server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
      SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
      mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
      mySqlConnection.Open();

      int returnValue = (int) mySqlCommand.ExecuteScalar();
      Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

      mySqlConnection.Close();




      We are using ExecuteScalar to return only ONE Cell. Remember, Even if your Query returns Multiple Rows/Columns, this will only returns VERY FIRST CELL always.






      share|improve this answer




















      • This appears to be C# code, but the question is tagged Java.
        – rgettman
        Aug 14 at 20:40










      Your Answer





      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );








       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51755129%2fwhy-is-while-rs-next-necessary-here%23new-answer', 'question_page');

      );

      Post as a guest






























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      69
      down vote



      accepted










      Why?



      The cursor is initially placed before the first element. You need to advance it once to access the first element.



      This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:




      Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.





      Solution



      So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:



      rs.next();
      // Access the result


      However, you probably want to account for the case where there was no match at all, since:




      When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.




      So the code would fail in this case.



      Because of that, you should account for the case and use the returned boolean to guard your access:



      if (rs.next()) 
      // Access result ...
      else
      // No match ...






      share|improve this answer


















      • 9




        A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
        – Andreas
        Aug 8 at 21:24






      • 3




        To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
        – Barranka
        Aug 9 at 12:20







      • 3




        @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
        – Lightness Races in Orbit
        Aug 9 at 12:41















      up vote
      69
      down vote



      accepted










      Why?



      The cursor is initially placed before the first element. You need to advance it once to access the first element.



      This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:




      Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.





      Solution



      So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:



      rs.next();
      // Access the result


      However, you probably want to account for the case where there was no match at all, since:




      When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.




      So the code would fail in this case.



      Because of that, you should account for the case and use the returned boolean to guard your access:



      if (rs.next()) 
      // Access result ...
      else
      // No match ...






      share|improve this answer


















      • 9




        A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
        – Andreas
        Aug 8 at 21:24






      • 3




        To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
        – Barranka
        Aug 9 at 12:20







      • 3




        @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
        – Lightness Races in Orbit
        Aug 9 at 12:41













      up vote
      69
      down vote



      accepted







      up vote
      69
      down vote



      accepted






      Why?



      The cursor is initially placed before the first element. You need to advance it once to access the first element.



      This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:




      Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.





      Solution



      So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:



      rs.next();
      // Access the result


      However, you probably want to account for the case where there was no match at all, since:




      When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.




      So the code would fail in this case.



      Because of that, you should account for the case and use the returned boolean to guard your access:



      if (rs.next()) 
      // Access result ...
      else
      // No match ...






      share|improve this answer














      Why?



      The cursor is initially placed before the first element. You need to advance it once to access the first element.



      This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:




      Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.





      Solution



      So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:



      rs.next();
      // Access the result


      However, you probably want to account for the case where there was no match at all, since:




      When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.




      So the code would fail in this case.



      Because of that, you should account for the case and use the returned boolean to guard your access:



      if (rs.next()) 
      // Access result ...
      else
      // No match ...







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 8 at 20:37

























      answered Aug 8 at 20:31









      Zabuza

      10.5k52538




      10.5k52538







      • 9




        A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
        – Andreas
        Aug 8 at 21:24






      • 3




        To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
        – Barranka
        Aug 9 at 12:20







      • 3




        @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
        – Lightness Races in Orbit
        Aug 9 at 12:41













      • 9




        A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
        – Andreas
        Aug 8 at 21:24






      • 3




        To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
        – Barranka
        Aug 9 at 12:20







      • 3




        @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
        – Lightness Races in Orbit
        Aug 9 at 12:41








      9




      9




      A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
      – Andreas
      Aug 8 at 21:24




      A select max(...) ... statement without a group by will always return exactly one row, even if no records match the where clause, in which case the returned value is null. So, a simple rs.next(); is perfectly correct for this SQL.
      – Andreas
      Aug 8 at 21:24




      3




      3




      To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
      – Barranka
      Aug 9 at 12:20





      To ensure clarity, I'd use if(rs.first()) ... . It would do exactly the same thing, but it would be much clearer to read.
      – Barranka
      Aug 9 at 12:20





      3




      3




      @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
      – Lightness Races in Orbit
      Aug 9 at 12:41





      @Andreas I would keep the check so the correctness of my Java is not dependent on the rules dictated by a different language. But I suppose that's personal preference. Actually I may consider skipping it in a performance-critical function if the branch is really causing trouble, but only with a comment above it indicating what the assumption is. At the very least this serves as protection the next time someone alters the SQL and doesn't think to revisit the logic of the surrounding Java code.
      – Lightness Races in Orbit
      Aug 9 at 12:41













      up vote
      20
      down vote













      From the official documentation (which you should have read btw):




      Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.




      You basically need to move it, in your case moving it once is enough:



       rs.next(); 
      System.out.println(rs.getInt("L"));





      share|improve this answer


























        up vote
        20
        down vote













        From the official documentation (which you should have read btw):




        Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.




        You basically need to move it, in your case moving it once is enough:



         rs.next(); 
        System.out.println(rs.getInt("L"));





        share|improve this answer
























          up vote
          20
          down vote










          up vote
          20
          down vote









          From the official documentation (which you should have read btw):




          Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.




          You basically need to move it, in your case moving it once is enough:



           rs.next(); 
          System.out.println(rs.getInt("L"));





          share|improve this answer














          From the official documentation (which you should have read btw):




          Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.




          You basically need to move it, in your case moving it once is enough:



           rs.next(); 
          System.out.println(rs.getInt("L"));






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 8 at 20:36

























          answered Aug 8 at 20:33









          Eugene

          55.6k976129




          55.6k976129




















              up vote
              9
              down vote













              You can convert this to use a simple if statement instead.



              if(rs.next()) 
              // other code here



              You would use while when you have more than one row to bring back.






              share|improve this answer
















              • 2




                No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
                – YCF_L
                Aug 8 at 20:33






              • 6




                @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
                – Mark Rotteveel
                Aug 8 at 20:37







              • 2




                @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
                – Mark Rotteveel
                Aug 8 at 20:42














              up vote
              9
              down vote













              You can convert this to use a simple if statement instead.



              if(rs.next()) 
              // other code here



              You would use while when you have more than one row to bring back.






              share|improve this answer
















              • 2




                No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
                – YCF_L
                Aug 8 at 20:33






              • 6




                @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
                – Mark Rotteveel
                Aug 8 at 20:37







              • 2




                @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
                – Mark Rotteveel
                Aug 8 at 20:42












              up vote
              9
              down vote










              up vote
              9
              down vote









              You can convert this to use a simple if statement instead.



              if(rs.next()) 
              // other code here



              You would use while when you have more than one row to bring back.






              share|improve this answer












              You can convert this to use a simple if statement instead.



              if(rs.next()) 
              // other code here



              You would use while when you have more than one row to bring back.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 8 at 20:32









              Makoto

              76.4k14119162




              76.4k14119162







              • 2




                No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
                – YCF_L
                Aug 8 at 20:33






              • 6




                @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
                – Mark Rotteveel
                Aug 8 at 20:37







              • 2




                @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
                – Mark Rotteveel
                Aug 8 at 20:42












              • 2




                No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
                – YCF_L
                Aug 8 at 20:33






              • 6




                @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
                – Mark Rotteveel
                Aug 8 at 20:37







              • 2




                @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
                – Mark Rotteveel
                Aug 8 at 20:42







              2




              2




              No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
              – YCF_L
              Aug 8 at 20:33




              No need for the if condition just rs.next(); int m = rs.getInt("L"); because max always return a result
              – YCF_L
              Aug 8 at 20:33




              6




              6




              @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
              – Mark Rotteveel
              Aug 8 at 20:37





              @YCF_L That depends on the exact query: consider an empty table, max without group by will return a single row with null, but with a group by it will return no row
              – Mark Rotteveel
              Aug 8 at 20:37





              2




              2




              @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
              – Mark Rotteveel
              Aug 8 at 20:42




              @MoritzBoth Sure, for the query in the question YCF_L is absolutely right, but given questions are - a lot of the time - simplified examples, you should consider the bigger picture as well. In this case, my response was triggered by the always in YCF_L's initial comment.
              – Mark Rotteveel
              Aug 8 at 20:42










              up vote
              8
              down vote














              A ResultSet cursor is initially positioned before the first row, the
              first call to the method next makes the first row the current row, the
              second call makes the second row the current row, and so on.




              consider you have something like this.



              ->1->2->3
              ^


              your "rs" is initially pointed before 1, when you call rs.next() it advances the arrow to point to 1



               ->1->2->3
              ^


              so if you do not call the next() method then you do not get the result.



              Hope this helps






              share|improve this answer


























                up vote
                8
                down vote














                A ResultSet cursor is initially positioned before the first row, the
                first call to the method next makes the first row the current row, the
                second call makes the second row the current row, and so on.




                consider you have something like this.



                ->1->2->3
                ^


                your "rs" is initially pointed before 1, when you call rs.next() it advances the arrow to point to 1



                 ->1->2->3
                ^


                so if you do not call the next() method then you do not get the result.



                Hope this helps






                share|improve this answer
























                  up vote
                  8
                  down vote










                  up vote
                  8
                  down vote










                  A ResultSet cursor is initially positioned before the first row, the
                  first call to the method next makes the first row the current row, the
                  second call makes the second row the current row, and so on.




                  consider you have something like this.



                  ->1->2->3
                  ^


                  your "rs" is initially pointed before 1, when you call rs.next() it advances the arrow to point to 1



                   ->1->2->3
                  ^


                  so if you do not call the next() method then you do not get the result.



                  Hope this helps






                  share|improve this answer















                  A ResultSet cursor is initially positioned before the first row, the
                  first call to the method next makes the first row the current row, the
                  second call makes the second row the current row, and so on.




                  consider you have something like this.



                  ->1->2->3
                  ^


                  your "rs" is initially pointed before 1, when you call rs.next() it advances the arrow to point to 1



                   ->1->2->3
                  ^


                  so if you do not call the next() method then you do not get the result.



                  Hope this helps







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 8 at 20:52

























                  answered Aug 8 at 20:37









                  Adithya Morampudi

                  926




                  926




















                      up vote
                      1
                      down vote













                      There are different types of Executing the Commands. Cursors are used to read the data from your executed queries. When you execute to Read, you using Forward Only Cursor by default hence you are only getting next result after calling Recorset.Next() ! I don't want to go in much deeper here. You can read about cursors here : https://docs.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado?view=sql-server-2017



                      The best solution in your case is to use Scalar Resultset which will return only ONE CELL thats exactly what you want to implement without having to loop through your result set. Following example shows how you can implement such :



                      using System;
                      using System.Data;
                      using System.Data.SqlClient;

                      class ExecuteScalar

                      public static void Main()

                      SqlConnection mySqlConnection =new SqlConnection("server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
                      SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                      mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
                      mySqlConnection.Open();

                      int returnValue = (int) mySqlCommand.ExecuteScalar();
                      Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

                      mySqlConnection.Close();




                      We are using ExecuteScalar to return only ONE Cell. Remember, Even if your Query returns Multiple Rows/Columns, this will only returns VERY FIRST CELL always.






                      share|improve this answer




















                      • This appears to be C# code, but the question is tagged Java.
                        – rgettman
                        Aug 14 at 20:40














                      up vote
                      1
                      down vote













                      There are different types of Executing the Commands. Cursors are used to read the data from your executed queries. When you execute to Read, you using Forward Only Cursor by default hence you are only getting next result after calling Recorset.Next() ! I don't want to go in much deeper here. You can read about cursors here : https://docs.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado?view=sql-server-2017



                      The best solution in your case is to use Scalar Resultset which will return only ONE CELL thats exactly what you want to implement without having to loop through your result set. Following example shows how you can implement such :



                      using System;
                      using System.Data;
                      using System.Data.SqlClient;

                      class ExecuteScalar

                      public static void Main()

                      SqlConnection mySqlConnection =new SqlConnection("server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
                      SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                      mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
                      mySqlConnection.Open();

                      int returnValue = (int) mySqlCommand.ExecuteScalar();
                      Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

                      mySqlConnection.Close();




                      We are using ExecuteScalar to return only ONE Cell. Remember, Even if your Query returns Multiple Rows/Columns, this will only returns VERY FIRST CELL always.






                      share|improve this answer




















                      • This appears to be C# code, but the question is tagged Java.
                        – rgettman
                        Aug 14 at 20:40












                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      There are different types of Executing the Commands. Cursors are used to read the data from your executed queries. When you execute to Read, you using Forward Only Cursor by default hence you are only getting next result after calling Recorset.Next() ! I don't want to go in much deeper here. You can read about cursors here : https://docs.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado?view=sql-server-2017



                      The best solution in your case is to use Scalar Resultset which will return only ONE CELL thats exactly what you want to implement without having to loop through your result set. Following example shows how you can implement such :



                      using System;
                      using System.Data;
                      using System.Data.SqlClient;

                      class ExecuteScalar

                      public static void Main()

                      SqlConnection mySqlConnection =new SqlConnection("server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
                      SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                      mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
                      mySqlConnection.Open();

                      int returnValue = (int) mySqlCommand.ExecuteScalar();
                      Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

                      mySqlConnection.Close();




                      We are using ExecuteScalar to return only ONE Cell. Remember, Even if your Query returns Multiple Rows/Columns, this will only returns VERY FIRST CELL always.






                      share|improve this answer












                      There are different types of Executing the Commands. Cursors are used to read the data from your executed queries. When you execute to Read, you using Forward Only Cursor by default hence you are only getting next result after calling Recorset.Next() ! I don't want to go in much deeper here. You can read about cursors here : https://docs.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado?view=sql-server-2017



                      The best solution in your case is to use Scalar Resultset which will return only ONE CELL thats exactly what you want to implement without having to loop through your result set. Following example shows how you can implement such :



                      using System;
                      using System.Data;
                      using System.Data.SqlClient;

                      class ExecuteScalar

                      public static void Main()

                      SqlConnection mySqlConnection =new SqlConnection("server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
                      SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                      mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
                      mySqlConnection.Open();

                      int returnValue = (int) mySqlCommand.ExecuteScalar();
                      Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

                      mySqlConnection.Close();




                      We are using ExecuteScalar to return only ONE Cell. Remember, Even if your Query returns Multiple Rows/Columns, this will only returns VERY FIRST CELL always.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 13 at 19:09









                      Nirmal Subedi

                      8492719




                      8492719











                      • This appears to be C# code, but the question is tagged Java.
                        – rgettman
                        Aug 14 at 20:40
















                      • This appears to be C# code, but the question is tagged Java.
                        – rgettman
                        Aug 14 at 20:40















                      This appears to be C# code, but the question is tagged Java.
                      – rgettman
                      Aug 14 at 20:40




                      This appears to be C# code, but the question is tagged Java.
                      – rgettman
                      Aug 14 at 20:40












                       

                      draft saved


                      draft discarded


























                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51755129%2fwhy-is-while-rs-next-necessary-here%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      這個網誌中的熱門文章

                      How to combine Bézier curves to a surface?

                      Mutual Information Always Non-negative

                      Why am i infinitely getting the same tweet with the Twitter Search API?