As we have seen, record-by-record retrieval can save a lot of overhead. To retrieve a data piecemeal using MySQL for Python, one can call one of two methods of the Cursor object: fetchone() or fetchmany().

The fetchone() method

The fetchone() method of a cursor object returns exactly one row of results. If the query affects no rows, None is returned. Consider the following code:

import MySQLdb
mydb = MySQLdb.connect(host = 'localhost',
user = 'skipper',
passwd = 'secret',
db = 'fish')
cur = mydb.cursor()
statement = "SELECT * FROM menu WHERE name='shark'"
result = cur.fetchone()
print result

The outcome will be a raw form of the first record that matches the query.

(11L, 'shark', Decimal('13.00')

Note that only the first ...

Get MySQL for Python now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.