ในบทความนี้ เราจะมาดู 4 ขั้นตอนในการโหลดข้อมูลจาก database ด้วย sqlalchemy และ pandas libraries ใน Python ผ่านตัวอย่างการทำงานกับ Chinook database กัน:
- Import libraries
- Connect to the database
- List the tables
- Get the table
ถ้าพร้อมแล้ว ไปเริ่มกันเลย
- ⬇️ 1. Import Libraries
- 🛜 2. Connect to the Database
- 📋 3. List the Tables
- 🪑 4. Get the Table
- 😺 GitHub
- 📃 References
⬇️ 1. Import Libraries
ในขั้นแรก เราจะโหลด sqlalchemy และ pandas กัน:
# Import packages
from sqlalchemy import create_engine, inspect
import pandas as pd
Note: ถ้ายังไม่เคยติดตั้ง libraries ให้ใช้คำสั่ง !pip install ก่อนใช้ import
🛜 2. Connect to the Database
ในขั้นที่ 2 เราจะเชื่อมต่อกับ database
ในตัวอย่าง เราจะเชื่อมต่อกับ SQLite database บนเครื่อง ซึ่งเราสามารถทำได้ด้วย create_engine() แบบนี้:
# Connect to the database
engine = create_engine("sqlite:///chinook.sqlite")
Note: ดาวน์โหลด chinook.sqlite ได้ที่ GitHub
📋 3. List the Tables
ในขั้นที่ 3 เราจะโหลดรายชื่อ tables ใน database เพื่อเลือก tables ที่เราต้องการ
เราจะใช้ 2 คำสั่ง ได้แก่:
inspect(): function สำหรับสร้าง object ที่เก็บ metadata ของ database เอาไว้.get_table_names(): method สำหรับแสดงรายชื่อ tables ใน database
# Get the inspector
inspector = inspect(engine)
# List the table names
tables = inspector.get_table_names()
# Print the table names
print(tables)
ผลลัพธ์:
['Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track']
🪑 4. Get the Table
ในขั้นสุดท้าย เราจะโหลดข้อมูลจาก table ที่ต้องการ โดยใช้ pd.read_sql():
# Set the query
brazil_customers_query = """
SELECT FirstName, LastName, Phone, Email
FROM Customer
WHERE Country = 'Brazil';
"""
# Query the database
df = pd.read_sql(brazil_customers_query, engine)
# Display the df
print(df)
ผลลัพธ์:
FirstName LastName Phone Email
0 Luís Gonçalves +55 (12) 3923-5555 luisg@embraer.com.br
1 Eduardo Martins +55 (11) 3033-5446 eduardo@woodstock.com.br
2 Alexandre Rocha +55 (11) 3055-3278 alero@uol.com.br
3 Roberto Almeida +55 (21) 2271-7000 roberto.almeida@riotur.gov.br
4 Fernanda Ramos +55 (61) 3363-5547 fernadaramos4@uol.com.br
😺 GitHub
ดูตัวอย่าง code ทั้งหมดได้ที่ GitHub

Leave a comment