使用 SQLAlchemy 從資料表擷取資料
到目前為止做得很棒!現在該用 SQLAlchemy 建立你的第一個 select 敘述了。SQLAlchemy 提供一種相當「Pythonic」的方式與資料庫互動。上一個練習你使用原生 SQL,直接對資料庫下查詢;而使用 SQLAlchemy 時,你會透過 Table 物件,讓 SQLAlchemy 自動把你的查詢轉換成合適的 SQL 敘述。這樣一來,你就不必處理 MySQL、PostgreSQL 等傳統 SQL 方言之間的差異,能善用 SQLAlchemy 的 Python 風格框架來簡化流程,更有效率地查詢資料。因此,即使你已經熟悉傳統 SQL,仍很值得學習。
在本練習中,你會再次建立一個查詢,用來擷取 census 資料表中的所有紀錄。不過這次你會使用 sqlalchemy 模組的 select() 函式。此函式唯一必填的引數是「表格或欄位的清單」:例如,select([my_table])。
你也會使用帶有 size 引數的 .fetchmany(),只抓取 ResultProxy 的少量紀錄,指定要抓取的筆數。
Table 與 MetaData 已經匯入。中介資料以 metadata 提供,且已以 connection 連線到資料庫。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
sqlalchemy模組匯入select。 - 映射(reflect)
census資料表。這段程式碼已為你寫好。 - 使用
select()函式建立查詢以擷取census資料表中的所有紀錄。為此,將只包含單一元素census的「清單」傳入select()。 - 列印
stmt,以查看實際產生的 SQL 查詢。這段程式碼已為你寫好。 - 從
census資料表抓取 10 筆紀錄並將其存入results。作法如下:- 對
connection使用.execute(),以stmt為引數來取得 ResultProxy。 - 在
connection.execute(stmt)上使用.fetchmany()並搭配適當的size引數來取得 ResultSet。
- 對
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import select
from ____ import ____
# Reflect census table via engine: census
census = Table('census', metadata, autoload=True, autoload_with=engine)
# Build select statement for census table: stmt
stmt = ____
# Print the emitted statement to see the SQL string
print(stmt)
# Execute the statement on connection and fetch 10 records: result
results = ____.____(____).____(size=___)
# Execute the statement and print the results
print(results)