使用 SQLAlchemy 建立資料表
先前你使用 Table 物件,從「既有」資料庫反射出一個資料表;但如果你想建立一個「新的」資料表呢?你一樣會使用 Table 物件;不過,需要把 autoload 與 autoload_with 參數改為使用 Column 物件。
Column 物件會接收名稱、SQLAlchemy 型別(可含選用的格式),以及用於不同限制條件的選用關鍵字引數。
在定義資料表時,回想影片中 Jason 如何用 Column('name', String(255)) 將字串的最大長度設為 255。回去看看該段投影片也會有幫助。
定義好資料表後,你可以在 metadata 上呼叫 .create_all(),並把 engine 當作唯一引數傳入,即可在資料庫中建立資料表。動手試試看吧!
本練習屬於課程
Python 資料庫入門
練習說明
- 從
sqlalchemy匯入Table、Column、String、Integer、Float、Boolean。 - 建立一個名為
data的新資料表,包含欄位'name'(String(255))、'count'(Integer())、'amount'(Float()),以及'valid'(Boolean())。Table()的第二個引數需要是已經初始化好的metadata。 - 將
engine傳入metadata.create_all(),在資料庫中建立該資料表。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import Table, Column, String, Integer, Float, Boolean from sqlalchemy
from sqlalchemy import ____, ____, ____, ____, ____, ____
# Define a new table with a name, count, amount, and valid column: data
data = Table('data', ____,
Column(____, ____),
Column('count', Integer()),
Column(____, ____),
Column(____, ____)
)
# Use the metadata to create the table
metadata.create_all(____)
# Print table details
print(repr(data))