การแทรกข้อมูลลงในตาราง

Python เบื้องต้นสำหรับฐานข้อมูล

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

การเพิ่มข้อมูลลงในตาราง

  • ใช้คำสั่ง insert()
  • insert() รับตารางที่ต้องการโหลดข้อมูลเป็น argument
  • เพิ่มค่าที่ต้องการแทรกใน values clause ในรูปแบบ column=value
  • ไม่คืนค่าแถวใด จึงไม่ต้องใช้ fetch method
Python เบื้องต้นสำหรับฐานข้อมูล

การแทรกข้อมูลหนึ่งแถว

from sqlalchemy import insert
stmt = insert(employees).values(id=1,name='Jason', 
          salary=1.00, active=True)

result_proxy = connection.execute(stmt) print(result_proxy.rowcount)
1
Python เบื้องต้นสำหรับฐานข้อมูล

การแทรกข้อมูลหลายแถว

  • สร้าง insert statement โดยไม่ระบุค่าใด
  • สร้าง list of dictionaries ที่แทน values clause ของแต่ละแถวที่ต้องการแทรก
  • ส่งทั้ง statement และ values list ไปยัง execute method บน connection
Python เบื้องต้นสำหรับฐานข้อมูล

การแทรกข้อมูลหลายแถว

stmt = insert(employees)

values_list = [{'id': 2, 'name': 'Rebecca', 'salary': 2.00, 'active': True}, {'id': 3, 'name': 'Bob', 'salary': 0.00, 'active': False}]
result_proxy = connection.execute(stmt, values_list)
print(result_proxy.rowcount)
2
Python เบื้องต้นสำหรับฐานข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับฐานข้อมูล

Preparing Video For Download...