After executing a `SELECT` query, `fetchone()` retrieves the next single row as a tuple (or `None` when exhausted), `fetchmany(size)` returns a list of at most `size` row tuples, and `fetchall()` returns a list of all remaining unread tuples. Meanwhile, `cur.rowcount` tracks the number of rows fetched so far on unbuffered cursors or total rows affected by `INSERT`/`UPDATE`/`DELETE`—not the total matched `SELECT` count prior to fetching.
- 1. How fetchone() and fetchmany(n) Advance the Internal Cursor Pointer
- 2. When to Choose fetchall() and How to Unpack Returned Tuples
- 3. Understanding cursor.rowcount Across SELECT and DML Queries
- 4. Demonstrating fetchone(), fetchmany(), fetchall(), and rowcount Progression
- 5. Comparison of Fetch Methods and rowcount Behavior
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. How fetchone() and fetchmany(n) Advance the Internal Cursor Pointer
Every cursor maintains a forward-only pointer over the current result set. Calling `cur.fetchone()` returns one row as a Python `tuple` (for example, `(101, 'Physics', 94)`) and advances that pointer by one position. If you invoke `fetchone()` inside a `while` loop until it returns `None`, you process huge tables in constant RAM without loading every record simultaneously. Similarly, `cur.fetchmany(size)` fetches up to `size` rows as a `list` of tuples—if only two rows remain and you call `fetchmany(5)`, it cleanly returns a two-element list, and a subsequent call returns an empty list `[]`. Note that if you call `fetchone()` once and then call `fetchall()`, `fetchall()` returns only the remaining unread rows, never the first row again, because the cursor pointer does not rewind automatically.
- `fetchone()` returns a `tuple` for a single record or `None` once the result set is exhausted.
- `fetchmany(n)` defaults to `n = 1` (controlled by `cur.arraysize`) and returns `[]` when no rows remain.
- Use `fetchone()` in a `while row:` loop when reading large result sets in batches.
2. When to Choose fetchall() and How to Unpack Returned Tuples
`cur.fetchall()` drains every unread row from the cursor and returns a `list` of tuples—for example, `[(1, 'Keyboard', 850), (2, 'Mouse', 450)]`—or an empty list `[]` if the query matched zero rows. In CBSE Class 12 CS board papers, `fetchall()` is the standard choice for reporting queries where you iterate with `for rec in rows:` and index columns as `rec[0]`, `rec[1]`, and so on, or check `if not rows:` to print a `'No record found'` message. One critical safeguard: `fetchall()` stores the entire query output in Python memory at once. While that is effortless for school-sized datasets of a few hundred records, pulling millions of rows with `fetchall()` can exhaust RAM, which is why paginated processing with `fetchmany(100)` is preferred in production services.
- `fetchall()` always returns a `list` (never `None`), making `len(rows)` safe even on zero matches.
- Unpack columns cleanly inside loops: `for pid, item, price in rows:` when column order is fixed.
- Avoid calling `fetchall()` twice on the same executed query; the second call always returns `[]`.
3. Understanding cursor.rowcount Across SELECT and DML Queries
Students frequently misread `cur.rowcount` in output-prediction questions because its value depends on both the SQL command type and whether rows have been fetched. Immediately after `cur.execute("SELECT ...")` on a default unbuffered cursor, `cur.rowcount` is `-1` because `mysql.connector` has not yet pulled the rows from the server. After calling `fetchone()`, `cur.rowcount` becomes `1`; after calling `fetchmany(2)`, it rises to `3`; and after `fetchall()`, it equals the total number of rows fetched. Conversely, for a buffered cursor (`con.cursor(buffered=True)`), `cur.rowcount` reflects the full `SELECT` count immediately after `execute()`. For DML statements (`INSERT`, `UPDATE`, `DELETE`), `cur.rowcount` reliably gives the exact integer count of rows inserted, modified, or deleted right after `execute()`, before you even call `commit()`.
- `cur.rowcount` is `-1` before fetching on an unbuffered `SELECT` cursor.
- Each `fetchone()` or `fetchmany(n)` increments `cur.rowcount` by the rows consumed so far.
- For `UPDATE` and `DELETE`, `cur.rowcount == 0` indicates no matching rows met the `WHERE` filter.
4. Demonstrating fetchone(), fetchmany(), fetchall(), and rowcount Progression
con = None
cur = None
try:
import mysql.connector as mc
con = mc.connect(
host="localhost",
user="root",
password="secret_password",
database="store_db",
)
cur = con.cursor()
cur.execute("SELECT item_id, item_name, price FROM items ORDER BY item_id")
print("Before fetch, rowcount:", cur.rowcount)
first_row = cur.fetchone()
print("fetchone():", first_row, "| rowcount:", cur.rowcount)
next_two = cur.fetchmany(2)
print("fetchmany(2):", next_two, "| rowcount:", cur.rowcount)
remaining = cur.fetchall()
print("fetchall():", remaining, "| rowcount:", cur.rowcount)
except Exception as err:
print("MySQL Status:", err)
finally:
if cur is not None:
cur.close()
if con is not None and con.is_connected():
con.close()
Verified Console / Dry-Run Output:
Before fetch, rowcount: -1
fetchone(): (1, 'Notebook', 60) | rowcount: 1
fetchmany(2): [(2, 'Marker', 45), (3, 'Compass', 120)] | rowcount: 3
fetchall(): [(4, 'Folder', 90), (5, 'Pen Set', 150)] | rowcount: 5
5. Comparison of Fetch Methods and rowcount Behavior
| Feature | Return Value (Rows Found) | Return Value (Exhausted) | Effect on rowcount |
|---|---|---|---|
| fetchone() | Single tuple (row) | None | Increments by 1 per row fetched |
| fetchmany(n) | List of up to n tuples | [] (empty list) | Increments by len(returned list) |
| fetchall() | List of all remaining tuples | [] (empty list) | Reaches total fetched row count |
| rowcount (unbuffered) | -1 right after SELECT | Total rows fetched at end | Tracks cumulative rows consumed |
| rowcount (DML) | Count of affected rows | 0 if no row matched WHERE | Available immediately after execute() |
Trace Python-MySQL Outputs With 1:1 Guidance
Join 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods) for a free 1:1 session solving CBSE CS 083 fetch and cursor tracing problems.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Treating `fetchone()` output as a list of tuples (`row[0][1]`) instead of indexing the single tuple directly (`row[1]`).
- Avoid Mistake: Assuming `cur.rowcount` gives the total `SELECT` row count immediately after `execute()` without fetching or buffering.
- Avoid Mistake: Calling `fetchall()` after `fetchone()` and expecting all rows, forgetting that `fetchone()` already consumed row 1.
- Avoid Mistake: Testing `if cur.fetchone() is []:` when exhausted; `fetchone()` returns `None`, whereas `fetchall()` and `fetchmany()` return `[]`.
- Examiner / Mentor Tip: In CBSE output-tracing questions, trace the cursor pointer row by row across `fetchone()`, `fetchmany()`, and `fetchall()`.
- Examiner / Mentor Tip: Remember that `cur.rowcount` is an attribute (no parentheses), NOT a method `cur.rowcount()`.
- Examiner / Mentor Tip: Prefer `len(rows)` after `fetchall()` when asked to print the exact number of matching records cleanly.
7. Interactive Concept Check Quiz
Question: Suppose a query matches 5 rows in an unbuffered cursor. If you call `cur.fetchone()` once and then `rows = cur.fetchall()`, what is `len(rows)` and `cur.rowcount`?
8. Frequently Asked Questions
Why does `cur.rowcount` return `-1` right after a `SELECT` query?
What happens if I call `fetchmany(10)` when only 3 rows exist?
Does `cur.fetchone()` return a tuple even when selecting only one column?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in CBSE CS (083) & IP (065) Hub
- Insert & Update MySQL Records From Python With commit()
- Safe Parameterized Queries Using the %s Placeholder in Python
- SQL String Functions: LEFT(), RIGHT(), MID(), and SUBSTR()
- Interactive Tool: CBSE CS 083 Python Output Predictor Quiz
- Interactive Tool: CBSE SQL GROUP BY / HAVING / JOIN Query Evaluator
