การแทรกแถวเดียว
มีหลายวิธีในการ insert ข้อมูลด้วย SQLAlchemy แต่เราจะเน้นวิธีที่ใช้รูปแบบเดียวกับคำสั่ง select
วิธีนี้ใช้คำสั่ง insert โดยระบุตารางเป็น argument และส่งข้อมูลที่ต้องการแทรกผ่านเมธอด .values() ในรูปแบบ keyword arguments ตัวอย่างเช่น หาก 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"
สังเกตความแตกต่างของ syntax: เมื่อเพิ่มคำสั่ง 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) ใน console เพื่อตรวจสอบโครงสร้างของตารางได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- Import
insertและselectจากโมดูลsqlalchemy - สร้าง insert statement ชื่อ
insert_stmtสำหรับตารางdataเพื่อกำหนดค่าnameเป็น'Anna',countเป็น1,amountเป็น1000.00และvalidเป็นTrue - Execute
insert_stmtด้วยconnectionแล้วเก็บผลลัพธ์ไว้ในตัวแปรresults - Print attribute
.rowcountของresultsเพื่อดูจำนวนแถวที่ถูกแทรก - สร้าง select statement เพื่อ query ข้อมูลจากตาราง
dataโดยค้นหาแถวที่มีnameเป็น'Anna' - รันโค้ดเพื่อแสดงผลลัพธ์ของการ execute select statement
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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())