Constraints และค่าเริ่มต้นของข้อมูล
ลองฝึกสร้างตารางพร้อมกำหนด constraints กันดู! บ่อยครั้งที่จำเป็นต้องกำหนดให้คอลัมน์มีค่าไม่ซ้ำกัน รับค่า null ได้หรือไม่ได้ มีค่าเป็นบวก หรือสัมพันธ์กับคอลัมน์ในตารางอื่น นั่นคือจุดที่ constraints เข้ามามีบทบาท
นอกจาก constraints แล้ว ยังสามารถกำหนดค่าเริ่มต้นให้กับคอลัมน์ได้ด้วย ในกรณีที่ไม่มีการส่งข้อมูลเข้ามา โดยใช้คีย์เวิร์ด default บนคอลัมน์นั้น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
Table,Column,String,Integer,Float,Booleanถูก import จากsqlalchemyเรียบร้อยแล้ว- สร้างตารางใหม่ชื่อ data โดยมีคอลัมน์
name(String) ที่ไม่ซ้ำกัน,count(Integer) ที่มีค่าเริ่มต้นเป็น1,amount(Float) และvalid(Boolean) ที่มีค่าเริ่มต้นเป็นFalse - กด ส่งคำตอบ เพื่อสร้างตารางในฐานข้อมูลและแสดงรายละเอียดของตาราง
data
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import Table, Column, String, Integer, Float, Boolean from sqlalchemy
from sqlalchemy import Table, Column, String, Integer, Float, Boolean
# Define a new table with a name, count, amount, and valid column: data
data = Table('data', metadata,
Column('name', String(255), unique=____),
Column('count', Integer(), default=____),
Column('amount', Float()),
Column('valid', Boolean(), default=____)
)
# Use the metadata to create the table
metadata.create_all(engine)
# Print the table details
print(repr(metadata.tables['data']))