Search code examples
mysqlpymysql

Bringing PyMySQL cursor to beginning


I am using PyMySQL 0.7.9 with MySQL 5.1.73. I have to do two operations using the same PyMySQL cursor. After first operation is complete on the cursor, I need to bring the cursor back to the beginning.

import pymysql;

cursor.execute("my query");
# First operation
for row in cursor :
  # run update query to update status flag for all rows fetched.

# Second Operation
for row in cursor : 
  # run some more commands for the rows.

I added

cursor.rownumber = 0
before the second operation. It worked. But is there any PyMySQL function by which I can achieve the same? Is there anything similar in PyMySQL to http://php.net/manual/en/mysqli-result.data-seek.php


Solution

  • According to the API definition, you can use the scroll function:

    cursor.scroll(value [, mode='relative' ])

    Scroll the cursor in the result set to a new position according to mode .

    If mode is relative (default), value is taken as offset to the current position in the result set, if set to absolute, value states an absolute target position.

    So to jump to the first row, you can use

    cursor.scroll(0, 'absolute')
    

    Internally, pymysql will actually just execute cursor.rownumber = 0 too.

    This will only work with a normal cursor, not with the unbuffered SScursor, where you (currently) can only scroll forward.