Why is âwhile (rs.next())â necessary here?
Clash Royale CLAN TAG#URR8PPP
up vote
29
down vote
favorite
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?
java jdbc
add a comment |Â
up vote
29
down vote
favorite
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?
java jdbc
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 toif (rs.next())
.
â shmosel
Aug 8 at 20:29
3
@shmosel orrs.next(); int m = rs.getInt("L");
â YCF_L
Aug 8 at 20:31
6
I'd codeif (!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
add a comment |Â
up vote
29
down vote
favorite
up vote
29
down vote
favorite
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?
java jdbc
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?
java jdbc
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 toif (rs.next())
.
â shmosel
Aug 8 at 20:29
3
@shmosel orrs.next(); int m = rs.getInt("L");
â YCF_L
Aug 8 at 20:31
6
I'd codeif (!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
add a comment |Â
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 toif (rs.next())
.
â shmosel
Aug 8 at 20:29
3
@shmosel orrs.next(); int m = rs.getInt("L");
â YCF_L
Aug 8 at 20:31
6
I'd codeif (!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
add a comment |Â
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 returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
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 ...
9
Aselect max(...) ...
statement without agroup by
will always return exactly one row, even if no records match thewhere
clause, in which case the returned value isnull
. So, a simplers.next();
is perfectly correct for this SQL.
â Andreas
Aug 8 at 21:24
3
To ensure clarity, I'd useif(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
add a comment |Â
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"));
add a comment |Â
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.
2
No need for the if condition justrs.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
withoutgroup by
will return a single row withnull
, but with agroup 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
add a comment |Â
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
add a comment |Â
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.
This appears to be C# code, but the question is tagged Java.
â rgettman
Aug 14 at 20:40
add a comment |Â
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 returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
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 ...
9
Aselect max(...) ...
statement without agroup by
will always return exactly one row, even if no records match thewhere
clause, in which case the returned value isnull
. So, a simplers.next();
is perfectly correct for this SQL.
â Andreas
Aug 8 at 21:24
3
To ensure clarity, I'd useif(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
add a comment |Â
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 returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
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 ...
9
Aselect max(...) ...
statement without agroup by
will always return exactly one row, even if no records match thewhere
clause, in which case the returned value isnull
. So, a simplers.next();
is perfectly correct for this SQL.
â Andreas
Aug 8 at 21:24
3
To ensure clarity, I'd useif(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
add a comment |Â
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 returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
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 ...
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 returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
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 ...
edited Aug 8 at 20:37
answered Aug 8 at 20:31
Zabuza
10.5k52538
10.5k52538
9
Aselect max(...) ...
statement without agroup by
will always return exactly one row, even if no records match thewhere
clause, in which case the returned value isnull
. So, a simplers.next();
is perfectly correct for this SQL.
â Andreas
Aug 8 at 21:24
3
To ensure clarity, I'd useif(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
add a comment |Â
9
Aselect max(...) ...
statement without agroup by
will always return exactly one row, even if no records match thewhere
clause, in which case the returned value isnull
. So, a simplers.next();
is perfectly correct for this SQL.
â Andreas
Aug 8 at 21:24
3
To ensure clarity, I'd useif(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
add a comment |Â
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"));
add a comment |Â
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"));
add a comment |Â
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"));
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"));
edited Aug 8 at 20:36
answered Aug 8 at 20:33
Eugene
55.6k976129
55.6k976129
add a comment |Â
add a comment |Â
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.
2
No need for the if condition justrs.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
withoutgroup by
will return a single row withnull
, but with agroup 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
add a comment |Â
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.
2
No need for the if condition justrs.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
withoutgroup by
will return a single row withnull
, but with agroup 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
add a comment |Â
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.
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.
answered Aug 8 at 20:32
Makoto
76.4k14119162
76.4k14119162
2
No need for the if condition justrs.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
withoutgroup by
will return a single row withnull
, but with agroup 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
add a comment |Â
2
No need for the if condition justrs.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
withoutgroup by
will return a single row withnull
, but with agroup 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
add a comment |Â
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
add a comment |Â
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
add a comment |Â
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
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
edited Aug 8 at 20:52
answered Aug 8 at 20:37
Adithya Morampudi
926
926
add a comment |Â
add a comment |Â
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.
This appears to be C# code, but the question is tagged Java.
â rgettman
Aug 14 at 20:40
add a comment |Â
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.
This appears to be C# code, but the question is tagged Java.
â rgettman
Aug 14 at 20:40
add a comment |Â
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.
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.
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
add a comment |Â
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
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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