Using SQL in Python Set up

Created
Sep 1, 2025 10:05 PM
Tags

🧰 Step 1: Install Required Packages

In your Jupyter environment (or terminal if using !pip):

bash
CopyEdit
pip install ipython-sql pymysql sqlalchemy

Or inside a notebook cell:

python
CopyEdit
!pip install ipython-sql pymysql sqlalchemy

🧠 Step 2: Load %sql Extension in Jupyter Notebook

In a notebook cell, load the SQL magic:

python
CopyEdit
%load_ext sql

🔗 Step 3: Connect to Your MySQL Database

Use the %sql line magic to connect. Replace classicmodels with your desired database if needed:

python
CopyEdit
%sql mysql+pymysql://root:Password1234@localhost:3306/classicmodels

You should see:

bash
CopyEdit
'Connected: root@classicmodels'

🧪 Step 4: Run SQL Queries Interactively

You can now run SQL using %%sql cell magic:

sql
CopyEdit
%%sql
SELECT customerName, creditLimit
FROM customers
WHERE creditLimit > 50000;

Or:

sql
CopyEdit
%%sql
SHOW TABLES;

📋 Optional: Save Results to a DataFrame

python
CopyEdit
result = %sql SELECT * FROM customers LIMIT 5
df = result.DataFrame()
df.head()

✅ Sample Session (All Together)

python
CopyEdit
!pip install ipython-sql pymysql sqlalchemy

%load_ext sql
%sql mysql+pymysql://root:Password1234@localhost:3306/classicmodels

%%sql
SELECT customerNumber, customerName, creditLimit
FROM customers
WHERE creditLimit > 75000;