Informatics Practices · Ch 3 — Data Handling using Pandas – II
Importing Data from MySQL to Pandas
Importing Data from MySQL to Pandas
The core idea is simple: you take a table that lives inside a MySQL database and pull it into your Python environment as a pandas DataFrame. Once the data is in a DataFrame, you can analyse, clean, and visualise it using all the pandas tools you have already learned.
The first step is always to establish a connection to the MySQL database. This is done using create_engine(), which returns a connection identifier (usually stored in a variable like sql_conn or engine). Once you have that connection, pandas gives you three different functions to bring the data across. Each serves a slightly different purpose.
The Three Functions for Importing Data
-
pandas.read_sql_query(query, sql_conn)This function takes a raw SQL query (written as a string) and executes it against the database. The result is returned directly as a DataFrame. Use this when you need to filter, join, or aggregate data on the database side before bringing it into Python. For example, you could write
"SELECT * FROM students WHERE city = 'Delhi'"as your query. -
pandas.read_sql_table(table_name, sql_conn)This function is simpler: you just give it the name of an existing table in the database, and it loads the entire table into a DataFrame. There is no SQL query involved — it is a direct table-to-DataFrame transfer. Use this when you want the whole table, without any filtering.
-
pandas.read_sql(sql, sql_conn)This is a flexible, combined function. The first argument (
sql) can be either a table name (likeread_sql_table) or a SQL query string (likeread_sql_query). The function automatically detects which one you have provided and acts accordingly. This is often the most convenient choice when you are not sure in advance whether you will need a query or a full table.
In all three functions, the second argument (sql_conn) is the connection identifier returned by create_engine(). Without a valid connection, none of these functions will work.
Summary Table
| Function | First Argument | What It Does |
|---|---|---|
read_sql_query() | A SQL query string | Executes the query and returns the result as a DataFrame. |
| Index | CarId | CarName | Price | Model | YearManufacture | Fueltype |
|---|---|---|---|---|---|---|
| 0 | D001 | Car1 | 582613.00 | LXI | 2017 | Petrol |
| 1 | D002 | Car1 | 673112.00 | VXI | 2018 | Petrol |
| 2 | B001 | Car2 | 567031.00 | Sigma1.2 | 2019 | Petrol |
| 3 | B002 | Car2 | 647858.00 | Delta1.2 | 2018 | Petrol |
| 4 | E001 | Car3 | 355205.00 | 5STR STD | 2017 | CNG |
| 5 | E002 | Car3 | 654914.00 | CARE | 2018 | CNG |
| 6 | S001 | Car4 | 514000.00 | LXI | 2017 | Petrol |
| 7 | S002 | Car4 | 614000.00 | VXI | 2018 | Petrol |