開始使用免費開始

從資料庫讀取

在這個練習中,你要從本機 PostgreSQL 資料庫的資料表擷取資料。你將使用的資料庫是 Pagila 範例資料庫。這個資料庫支援一個虛構的 DVD 商店應用程式,常被教學資源當作示例資料庫。

你會建立並使用一個函式,把資料庫中的資料表擷取成一個 pandas 的 DataFrame 物件。你要擷取的資料表有:

  • film:DVD 商店可供出租的電影。
  • customer:在 DVD 商店租借電影的顧客。

為了連線到資料庫,你必須使用 PostgreSQL 連線 URI,格式類似下面這樣:

postgresql://[user[:password]@][host][:port][/database]

本練習屬於課程

Data Engineering 入門

檢視課程

練習說明

  • 完成 extract_table_to_pandas() 的函式定義,將參數 tablename 納入查詢中。
  • 填入連線 URI。使用者名稱與密碼分別是 replpassword。主機是 localhost,連接埠為 5432,資料庫是 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)
編輯並執行程式碼