Skip to content
Exercises · Q10

Q.Write the steps required to read data from a MySQL database to a DataFrame.

Yanam CbseNCERTSubjective· 3mImportance★★★★★
57% · 30/53 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

To read MySQL data into a pandas DataFrame, you connect to the database using mysql.connector or pymysql, execute a SELECT query, and pass the cursor to pd.read_sql() — which handles the conversion automatically.

This is a plain theory question — it asks for the steps, not code output. The core idea is that pandas provides a direct bridge between SQL result sets and DataFrames, eliminating the need to manually iterate through rows.

Why pd.read_sql() is the right tool

When you execute a SQL query in Python, the database driver returns a cursor object containing rows. Manually converting these rows into a DataFrame would require:

  • Fetching all rows with cursor.fetchall()
  • Extracting column names from cursor.description
  • Building a list of dictionaries or tuples
  • Passing them to pd.DataFrame()

pd.read_sql() does all of this in one call. It accepts either a connection object (not a cursor) or a SQLAlchemy engine, executes the query, and returns a DataFrame with proper column names and data types.

Step-by-step process

Step 1: Install and import the required library

You need a MySQL connector. The two most common are mysql-connector-python (official Oracle) and pymysql. Import pandas and the connector:

import pandas as pd
import mysql.connector  # or import pymysql

Step 2: Establish a connection to the MySQL database

Create a connection object by providing host, user, password, and database name:

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="your_password",
    database="school_db"
)
Watch out

Never hardcode credentials in production code. Use environment variables or a config file. Also, always close the connection after use to avoid resource leaks.

Step 3: Write the SQL query

Define the SELECT statement that fetches the data you need:

query = "SELECT * FROM students WHERE grade = 'A'"

Step 4: Use pd.read_sql() to read into a DataFrame

Pass the query and the connection object. The function executes the query and returns a DataFrame:

df = pd.read_sql(query, conn)

Step 5: Close the connection

Always close the connection when done:

conn.close()

Alternative: Using SQLAlchemy engine

For more complex applications, use SQLAlchemy's create_engine():

from sqlalchemy import create_engine

engine = create_engine("mysql+mysqlconnector://root:password@localhost/school_db")
df = pd.read_sql("SELECT * FROM students", engine)
Tip

Using an engine is preferred when you need to execute multiple queries or write DataFrames back to the database with df.to_sql(). The engine manages connection pooling automatically.

Complete working example

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.