開始使用免費開始

從資料表選取資料:raw SQL

正如你在影片中看到的,要存取並操作資料庫中的資料,我們需要先透過在 engine 上呼叫 .connect() 方法來建立連線。原因是你先前使用的 create_engine() 會回傳一個 engine 物件,但在需要連線的動作(例如查詢)被呼叫之前,實際的連線並不會開啟。

利用剛學到的 SQL,並在連線上使用 .execute() 方法,我們可以透過 raw SQL 查詢 census 資料表中的所有紀錄。.execute() 方法所回傳的物件是 ResultProxy。在這個 ResultProxy 上,我們可以再呼叫 .fetchall() 取得查詢結果,也就是 ResultSet

在這個練習中,你會使用傳統的 SQL 查詢。請注意,當你使用 raw SQL 來執行查詢時,會直接在資料庫中查詢該資料表。特別是,不需要進行反射(reflection)步驟。

下一個練習你將改用 SQLAlchemy,並開始了解它的優勢。開始吧!

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • 使用 engine.connect() 方法建立連線。
  • 建立一段 SQL 陳述式以查詢 census 中「所有」欄位,並將其字串存成 stmt。請注意,SQL 陳述式必須是「字串」。
  • connection 上依序使用 .execute().fetchall(),並把結果存到 results。記得要先 .execute().fetchall(),而且要把 stmt 傳入 .execute()
  • 列印 results

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

from sqlalchemy import create_engine
engine = create_engine('sqlite:///census.sqlite')

# Create a connection on engine
connection = ___

# Build select statement for census table: stmt
stmt = ____

# Execute the statement and fetch the results: results
results = ____

# Print results
print(____)
編輯並執行程式碼