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 result will be printed using the preceding code. As the query leaves us vulnerable if there is more than one result, this is undesirable. If we are only going to process one record...