Read Operation

The SELECT statement is used to retrieve data from a table in a MySQL database. Let's see how to fetch and display data using Python.

Example: Reading Data from the 'students' Table


import mysql.connector

# Establishing a connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    database='student_db'
)
cursor = connection.cursor()

# Reading data from the 'students' table
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()

print("Data in 'students' table:")
for row in rows:
    print(row)

cursor.close()
connection.close()
            

Output

Data in 'students' table: (1, 'Alice', 20, 'A') (2, 'Bob', 22, 'B') (3, 'Charlie', 21, 'A')