เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การแทรกแถวเดียว

มีหลายวิธีในการ 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())
แก้ไขและรันโค้ด