tags:

views:

164

answers:

1

I'm using MySQLdb library to connect to MySQL within my Python script.

(Ref: http://mysql-python.sourceforge.net/MySQLdb.html ).

I would like to learn if there is a way to jump to the last record in a resultset using Python?
In other words, I would like to move my cursor to the last record in the resultset.

+1  A: 

Well, your question is weird. Why would you want to do that?

You could keep reading records from the cursor until it is the last. But you'd have to try reading past it to know it is the last one, you can't know before reading it.

Another idea is to make a reversed query. Use ORDER BY to reverse the result order and the last will come first.

Or if you know the number of records, you could use OFFSET to return only the last one. You could issue a COUNT query first to know the number, and then use this number on OFFSET.

nosklo
And don't forget to use `LIMIT` so that you only fetch the record you are interested in and not the whole table.
Antoine P.
I don't think the first two solutions would be efficient on large databases. The third solution (OFFSET) is interesting, that's probably what I'm looking for since Python's MySQL API does not provide functions such as afterLast(), beforeFirst() which are pretty common in some other programming languages.
Haluk