自訂 SQL 查詢的 Hello World
恭喜你執行了第一個 SQL 查詢!接下來你要學會如何自訂查詢,以便:
- 從資料表中選取特定欄位;
- 選取特定筆數的列;
- 從資料庫資料表匯入欄位名稱。
回想一下,Hugo 在影片中做過非常類似的查詢自訂:
engine = create_engine('sqlite:///Northwind.sqlite')
with engine.connect() as con:
rs = con.execute("SELECT OrderID, OrderDate, ShipName FROM Orders")
df = pd.DataFrame(rs.fetchmany(size=5))
df.columns = rs.keys()
所需套件已經如下匯入:
from sqlalchemy import create_engine
import pandas as pd
引擎也已經建立:
engine = create_engine('sqlite:///Chinook.sqlite')
引擎連線已由下列敘述開啟:
with engine.connect() as con:
你需要完成的所有程式碼都在這個區塊中。
本練習屬於課程
Python 資料匯入入門
練習說明
- 執行一個 SQL 查詢,從
Employee資料表中選取(SELECT)欄位LastName和Title,並將結果存成變數rs。 - 對
rs使用fetchmany()方法以擷取 3 筆紀錄,並將其存入 DataFramedf。 - 使用
rs物件,將 DataFrame 的欄名設為對應的資料表欄位名稱。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Open engine in context manager
# Perform query and save results to DataFrame: df
with engine.connect() as con:
rs = ____
df = pd.DataFrame(____)
df.columns = ____
# Print the length of the DataFrame df
print(len(df))
# Print the head of the DataFrame df
print(df.head())