2

Actually I have executed the postgres query, assume that it has return the 10 rows. Now I am having that's statement handler ( $sth ) .

print Dumper $sth->fetchrow_arrayref;
print Dumper $sth->fetchrow_arrayref;
print Dumper $sth->fetchrow_arrayref;
print Dumper $sth->fetchrow_arrayref;
print Dumper $sth->fetchrow_arrayref;

Now , I have fetched the 5 rows from the statement handler ( $sth .Now I want to get back $sth reference pointer to 1th row.....

What should I do....?

Thanks

3 Answers 3

5

You cannot do that. Database cursors are designed to be read row by row, like a stream, without rewinding.

You need to copy the data into an array in memory if you want to jump around.

The easiest way would be to do

my $all_rows = $sth->fetchall_arrayref;

which gives you an arrayref, with one entry for each row, each row in the same format as fetchrow_arrayref produced.

Sign up to request clarification or add additional context in comments.

3 Comments

Will this actually work? I have been told that for arrayref the same array reference is used each time. so you cannot store the array reference and use it later, as the data behind it is being overwritten. But I am I trying to confirm this.
Just ran a test, and I can verify at at least in some instances you cannot just store the reference. As it is the same reference every time. The documentation says this: "Note that the same array reference is returned for each fetch, so don't store the reference and then use it after a later fetch. Also, the elements of the array are also reused for each row, so take care if you want to take a reference to an element." Not that there is anything wrong with this exact example, just combining it with the original posters code.
Yes, if you fetch a single row, you don't want to store that reference, as it will be re-used when you fetch the next one. "fetchall" should be safe, though.
1

In a while loop.

  1. Fetch row.
  2. If it is something you want to keep, copy the results to a save list.
  3. Refer to the save list whenever you want to reference a previous row.

Comments

0

another way to process your query's result's, you can loop over it :

while(my $res = $sth->fetchrow_arrayref()) {do something}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.