• Post Reply Bookmark Topic Watch Topic
  • New Topic

retrieve only one result (line) db  RSS feed

 
ronald silva
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi.
using servlet-postgresql, I can retrieve several lines, through the "result set rs = ps.executeQuery()" and "while (rs.next())".
but, I want retrieve one only line. without using "while(rs.next())".
is it possible?

for example, I have a table "mytable" with 5 lines:
ID / name / profession
1 / mariah / student
2 / john / teacher
3 / angelina / actress
4 / bob / policeman
5 / samantha / actress

if I do a "select name from mytable where id = 3", I hope to retrieve only one line (angeline).
how do I do this, without using "while(rs.next)"?
because I know the result it will be  only one line. I dont need to do a loop inside the results to find the line-result.
imagine if I have a table with thounsad lines. I want retrieve one line through the "id". is it possible?



 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66158
146
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is it about .next() that's not satisfying your need?
 
ronald silva
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why I dont want to use "rs.next()"?

imagine that I have a table  with 1 million of lines.
I want to retrieve just ONE only line.
why should I read all lines in the table using rs.next?
couldnt I retrieve just the line that interests to me? it is the line with especific "id".
if the line that I want is the third line, I need continue read all others lines after the third line?
it is a such waste of time.

 
Ron McLeod
Saloon Keeper
Posts: 1564
222
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ronald silva wrote:imagine that I have a table  with 1 million of lines.
I want to retrieve just ONE only line.
why should I read all lines in the table using rs.next?
couldnt I retrieve just the line that interests to me? it is the line with especific "id".
if the line that I want is the third line, I need continue read all others lines after the third line?

In the example you gave, using select name from mytable where id = 3, the result set would contain exactly one row.  Same with a table with a million rows, as long as your query is specific enough to one match on a single entry, the result set will only contain one row, and rs.next() will return false after the cursor moved beyond that one row.

If you know that either either zero or one rows will be returned, or if you are only interested in the first row if many are returned, then you could use if rather than while.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!