Python MySQL Select From Table
In this page:
cursor.execute("SELECT column1, column2 FROM table_name")
rows = cursor.fetchall()
Selecting All Columns
cursor.execute("SELECT * FROM customers") followed by cursor.fetchall() retrieves every column of every row in the customers table as a list of tuples, one tuple per row, giving you the complete contents of the table in Python.
Example: Selecting All Columns
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
cursor.fetchall.return_value = [(1, "John", "Highway 21")]
print(cursor.fetchall()) # every column of every row, as a list of tuples
Using fetchone() for a Single Row
cursor.fetchone() retrieves just the next single row from the result set (or None if there are no more rows), a good choice when you know or expect exactly one matching row, such as looking up a user by a unique ID.
Example: Using fetchone() for a Single Row
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers WHERE id = %s", (1,))
cursor.fetchone.return_value = (1, "John", "Highway 21")
print(cursor.fetchone()) # just the next single row, or None
Iterating the Cursor Directly
A cursor object is itself iterable after execute() runs -- looping over it directly with a for statement fetches rows one at a time under the hood, which is memory-efficient for large result sets since it avoids loading everything into a list at once.
Example: Iterating the Cursor Directly
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
cursor.__iter__.return_value = iter([(1, "John"), (2, "Amy")])
for row in cursor: # fetches rows one at a time instead of loading them all at once
print(row)
Accessing Results as Dictionaries
mysql.connector.connect(..., dictionary=True) as a cursor argument (or conn.cursor(dictionary=True)) makes each fetched row come back as a dict keyed by column name instead of a plain tuple, which is often more readable than remembering positional tuple indexes.
Example: Accessing Results as Dictionaries
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor(dictionary=True) # rows come back as dicts keyed by column name
cursor.execute("SELECT * FROM customers")
cursor.fetchall.return_value = [{"id": 1, "name": "John"}]
for row in cursor.fetchall():
print(row["name"])
Counting Result Rows
cursor.rowcount, read after fetching results from a SELECT, reports how many rows the query returned -- useful for quickly checking whether any matching rows exist at all without inspecting the full fetched data.
Example: Counting Result Rows
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
cursor.fetchall.return_value = [(1,), (2,), (3,)]
rows = cursor.fetchall()
cursor.rowcount = len(rows)
print(cursor.rowcount) # how many rows the query returned
- Calling cursor.execute() for a SELECT but never actually calling a fetch method afterward, leaving the results unread.
- Using fetchall() on a table with millions of rows, loading the entire result set into memory at once instead of fetching in smaller batches or iterating the cursor directly.
- Forgetting that column order in the result tuples matches the order columns were listed in the SELECT statement (or the table's column order for SELECT *), not alphabetical order.
- cursor.execute("SELECT * FROM table") runs a query that selects every column from every row in a table.
- cursor.fetchall() retrieves every row from the last executed query as a list of tuples.
- cursor.fetchone() retrieves just the single next row, useful when you expect (or only need) one result.
SELECT syntax and the fetch methods described here work identically across all supported mysql-connector-python versions.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Python MySQL Get Started
- Python MySQL Create Database
- Python MySQL Create Table
- Python MySQL Insert Into Table
- Python MySQL Select From Table
- Python MySQL Select With a Filter
- Python MySQL Order By
- Python MySQL Delete Record
- Python MySQL Drop Table
- Python MySQL Update Table
- Python MySQL Limit
- Python MySQL Join