Why rs.next() before fetching data???

P

parkarumesh

Hi,

I have written a function as follows

public String fetchName(String query) throws Exception
{

stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
return (rs.getString(1));
}

If i don't write the statement,
rs.next and directly use rs.getString(1), i get exception

Why is it so, why do we need to move one record next???

Thanks
 
I

Ingo R. Homann

Hi,

I have written a function as follows

public String fetchName(String query) throws Exception
{

stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
return (rs.getString(1));
}

If i don't write the statement,
rs.next and directly use rs.getString(1), i get exception

Why is it so, why do we need to move one record next???

Because

(1) There may be more than one record in the result set.
(2) There may be no record in the result set.

You must be able to handle that!

Ciao,
Ingo
 
C

Chris Diver

Hi,

I have written a function as follows

public String fetchName(String query) throws Exception
{

stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
return (rs.getString(1));
}

If i don't write the statement,
rs.next and directly use rs.getString(1), i get exception

Why is it so, why do we need to move one record next???

Thanks
I'm not entirely sure why it is. I'd imagine its a pointer
which starts before the first tuple in your result set.

Initially
-->
Row1
Row2
Row3
....

Calling rs.next() moves the pointer down.

....
--> Row1
Row2
....


But it does allow you to do

while(rs.next()){
//get elements
}

because rs.next() returns true when there is
another row and false if there was no next row.

Chris
 
Joined
Dec 31, 2007
Messages
2
Reaction score
0
A related question

I am doing something similar to this.. however what I want is to delete all except the last from the result set of a query I am executing.

My sql query gives a list of names that I want to delete except for the last one which I want to keep.

Is there something like rs->getlast() as well which would give me the last name from that result set? How do I implement this?

Appreciate your help
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top