O'Reilly logo

MySQL for Python by Albert Lukaszewski, PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How?

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'"
cur.execute(statement)
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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required