插入單一列
使用 SQLAlchemy 進行插入有多種方式;不過,這裡我們要專注在一種與 select 陳述式相同模式的方法。
它使用 insert 陳述式,將資料表作為引數傳入,並透過 .values() 方法以關鍵字引數提供你要插入的資料。例如,若 my_table 包含欄位 my_col_1 與 my_col_2,則 insert(my_table).values(my_col_1=5, my_col_2="Example") 會在 my_table 中建立一列,使 my_col_1 的值為 5,my_col_2 的值為 "Example"。
請留意語法差異:當在既有陳述式後面接上一個 where 條件時,我們會同時包含「資料表名稱」與欄位名稱,例如 new_stmt = old_stmt.where(my_tbl.columns.my_col == 15)。這是必要的,因為既有陳述式可能涉及多個資料表。
相對地,insert 一次只能將紀錄插入到單一資料表,因此在使用 values() 插入時不需要包含資料表名稱,例如 stmt = insert(my_table).values(my_col = 10)。
在本題中,資料表名稱為 data。你可以在主控台執行 repr(data) 來檢視該資料表的結構。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
sqlalchemy模組匯入insert與select。 - 為
data資料表建立插入陳述式insert_stmt,將name設為'Anna'、count設為1、amount設為1000.00、valid設為True。 - 使用
connection執行insert_stmt,並將結果儲存到results。 - 列印
results的.rowcount屬性,查看插入了多少筆紀錄。 - 建立一個 select 陳述式,查詢
data中name為'Anna'的紀錄。 - 執行解答以列印執行該 select 陳述式的結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import insert and select from sqlalchemy
from sqlalchemy import ____, ____
# Build an insert statement to insert a record into the data table: insert_stmt
insert_stmt = insert(____).values(name=____, ____, ____, ____)
# Execute the insert statement via the connection: results
results = connection.execute(____)
# Print result rowcount
print(____)
# Build a select statement to validate the insert: select_stmt
select_stmt = select([data]).where(____ == ____)
# Print the result of executing the query.
print(connection.execute(select_stmt).first())