Python MySQL cursor.fetchall() Explained with Examples

The cursor.fetchall() method is used to fetch all rows of a query result set as a list of tuples.

Syntax

rows = cursor.fetchall()

Return Value

It returns a list of tuples, where each tuple represents a row from the query result set. If no rows are available, an empty list is returned.

Fetching and Printing All Rows

import mysql.connector

# Establish connection to MySQL server
connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="mydatabase"
)

cursor = connection.cursor()

# Execute a SELECT query
cursor.execute("SELECT * FROM users")

# Fetch all rows
rows = cursor.fetchall()

# Print all rows
for row in rows:
    print(row)

connection.close()