开发者

How to move my cursor to the last record in MySQL using Python?

开发者 https://www.devze.com 2022-12-15 15:07 出处:网络
I\'m using MySQLdb library to connect to MySQL within my Python script. (Ref: http://mysql-python.sou开发者_运维知识库rceforge.net/MySQLdb.html ).

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

(Ref: http://mysql-python.sou开发者_运维知识库rceforge.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.


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.


If you feel the query is not too hard on the db, and there is enough memory on the machine, you could store the result set in a list, and just grab the last object from the list:

import MySQLdb
conn = MySQLdb.connect(host='',user='',passwd='')
curs = conn.cursor()
curs.execute('show databases') # or whatever query
last_result = [x[0] for x in curs.fetchall()][-1]


curs.execute("SELECT ghfhgf")

return an int with the number of records.

To move from one records to another x steps

curs.scroll(x)

So

curs.scroll(curs.execute("SELECT hgffg"))

Can work for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消