อ่านข้อมูลจากฐานข้อมูล
ในแบบฝึกหัดนี้ จะได้ดึงข้อมูลที่เก็บอยู่ในตารางของฐานข้อมูล PostgreSQL ในเครื่อง โดยใช้ Pagila example database ซึ่งเป็นฐานข้อมูลสำหรับแอปพลิเคชันร้านเช่า DVD สมมติ และมักถูกใช้เป็นตัวอย่างในสื่อการเรียนรู้ต่างๆ
จะสร้างและใช้ฟังก์ชันที่ดึงข้อมูลจากตารางในฐานข้อมูลมาเป็น DataFrame ของ pandas โดยตารางที่จะดึงข้อมูล ได้แก่
film: รายการภาพยนตร์ที่ให้เช่าในร้าน DVDcustomer: ข้อมูลลูกค้าที่เช่าภาพยนตร์จากร้าน
ในการเชื่อมต่อกับฐานข้อมูล จะต้องใช้ PostgreSQL connection URI ซึ่งมีรูปแบบดังนี้
postgresql://[user[:password]@][host][:port][/database]
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Data Engineering เบื้องต้น
คำแนะนำการฝึกหัด
- เติมนิยามของฟังก์ชัน
extract_table_to_pandas()ให้ครบ โดยใส่อาร์กิวเมนต์tablenameลงในคิวรี - กำหนด connection URI โดย username และ password คือ
replและpasswordตามลำดับ host คือlocalhostport คือ5432และ database คือpagila - เติมการเรียกใช้ฟังก์ชัน
extract_table_to_pandas()เพื่อดึงข้อมูลจากตาราง film และ customer
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Function to extract table to a pandas DataFrame
def extract_table_to_pandas(tablename, db_engine):
query = "SELECT * FROM {}".format(____)
return pd.read_sql(query, db_engine)
# Connect to the database using the connection URI
connection_uri = "postgresql://____:____@____:____/____"
db_engine = sqlalchemy.create_engine(connection_uri)
# Extract the film table into a pandas DataFrame
extract_table_to_pandas("____", db_engine)
# Extract the customer table into a pandas DataFrame
extract_table_to_pandas("____", db_engine)