SELECT reads data from a table. In this tutorial you will fetch all rows, chosen columns, one row at a time, and get results as dictionaries.
Prerequisites
The customers table with some rows from Insert Into Table.
Select All Rows
import mysql.connector
mydb = mysql.connector.connect(
host='localhost',
user='root',
password='your_password',
database='itronix'
)
mycursor = mydb.cursor()
mycursor.execute('SELECT * FROM customers')
myresult = mycursor.fetchall()
for row in myresult:
print(row)
Explanation: * means all columns. fetchall() returns a list of tuples, one per row. Your rows depend on what you inserted.
(1, 'Asha', 'Ludhiana') (2, 'Kevin', 'Dublin') ...
Select Specific Columns
mycursor.execute('SELECT name, address FROM customers')
for name, address in mycursor.fetchall():
print(name, '-', address)
Fetch One Row
mycursor.execute('SELECT * FROM customers')
first = mycursor.fetchone()
print(first)
mycursor.fetchall() # read the rest before the next query
Explanation: fetchone() returns the next row or None. Read or discard all remaining rows before running another query, or you get “Unread result found”.
Results as Dictionaries
cur = mydb.cursor(dictionary=True)
cur.execute('SELECT * FROM customers')
for row in cur.fetchall():
print(row['name'], row['address'])
Explanation: With dictionary=True you access columns by name, which is clearer than tuple indexes.
Load into Pandas
import pandas as pd
cur = mydb.cursor()
cur.execute('SELECT * FROM customers')
df = pd.DataFrame(cur.fetchall(), columns=[c[0] for c in cur.description])
print(df.head())
Explanation: cursor.description holds the column names. This is the usual first step of data analysis on database data.
Count Rows
mycursor.execute('SELECT COUNT(*) FROM customers')
print(mycursor.fetchone()[0])
Common Errors
| Problem | Cause and fix |
|---|---|
InternalError: Unread result found |
Fetch all rows of the previous query before executing another. |
ModuleNotFoundError: No module named 'mysql' |
Run pip install mysql-connector-python. |
Access denied for user 'root'@'localhost' |
Wrong user name or password. |
Can't connect to MySQL server on 'localhost' |
The MySQL server is not running. Start it from MySQL Workbench, XAMPP or your system services. |
Unknown database 'itronix' |
Create the database first (see Create Database). |
Practice Exercises
- Print only the names in alphabetical order (see Order By).
- Load the table into a Pandas DataFrame and print its shape.
Interview Questions
Q: fetchone vs fetchall?
fetchone returns the next row; fetchall returns all remaining rows as a list.
Summary
Execute SELECT, then read results with fetchall() or fetchone(); use dictionary=True for named columns.
Machine Learning Tutorials, Courses and Certifications