Documentation Home
MySQL Connector/Python Developer Guide
Related Documentation Download this Manual
PDF (US Ltr) - 0.7Mb
PDF (A4) - 0.7Mb


10.5.11 MySQLCursor.fetchone() Method

Syntax:

row = cursor.fetchone()

This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects. If the cursor is a raw cursor, no such conversion occurs; see Section 10.6.2, “cursor.MySQLCursorRaw Class”.

The fetchone() method is used by fetchall() and fetchmany(). It is also used when a cursor is used as an iterator.

The following example shows two equivalent ways to process a query result. The first uses fetchone() in a while loop, the second uses the cursor as an iterator:

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)

You must fetch all rows for the current query before executing new statements using the same connection.