การสร้างฐานข้อมูลและตาราง

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

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

การสร้างฐานข้อมูล

  • ขึ้นอยู่กับประเภทของฐานข้อมูล
  • ฐานข้อมูลอย่าง PostgreSQL และ MySQL มีเครื่องมือ command-line สำหรับสร้างฐานข้อมูล
  • ใน SQLite คำสั่ง create_engine() จะสร้างฐานข้อมูลและไฟล์ให้อัตโนมัติหากยังไม่มี
Python เบื้องต้นสำหรับฐานข้อมูล

การสร้างตาราง

from sqlalchemy import (Table, Column, String, 
       Integer, Decimal, Boolean)

employees = Table('employees', metadata, Column('id', Integer()), Column('name', String(255)), Column('salary', Decimal()), Column('active', Boolean()))
metadata.create_all(engine)
engine.table_names()
[u'employees']
Python เบื้องต้นสำหรับฐานข้อมูล

การสร้างตาราง

  • ยังคงใช้ออบเจกต์ Table เหมือนกับตอนทำ reflection
  • แทนที่อาร์กิวเมนต์ autoload ด้วยออบเจกต์ Column
  • สร้างตารางในฐานข้อมูลจริงโดยใช้เมธอด create_all() บน MetaData instance
  • ต้องใช้เครื่องมืออื่นสำหรับอัปเดตตาราง เช่น Alembic หรือ SQL โดยตรง
Python เบื้องต้นสำหรับฐานข้อมูล

การสร้างตาราง - ตัวเลือกคอลัมน์เพิ่มเติม

  • unique บังคับให้ค่าทุกแถวในคอลัมน์ไม่ซ้ำกัน
  • nullable กำหนดว่าคอลัมน์นั้นเว้นว่างได้หรือไม่
  • default กำหนดค่าเริ่มต้นหากไม่มีการระบุค่า
Python เบื้องต้นสำหรับฐานข้อมูล

การสร้างตารางพร้อมตัวเลือกเพิ่มเติม

employees = Table('employees', metadata,
       Column('id', Integer()), 
       Column('name', String(255), unique=True, nullable=False), 
       Column('salary', Float(), default=100.00),          
       Column('active', Boolean(), default=True))

employees.constraints
{CheckConstraint(... 
Column('name', String(length=255), table=<employees>, nullable=False), 
Column('salary', Float(), table=<employees>, 
       default=ColumnDefault(100.0)), 
Column('active', Boolean(), table=<employees>, 
       default=ColumnDefault(True)), ...
UniqueConstraint(Column('name', String(length=255), 
                 table=<employees>, nullable=False))}
Python เบื้องต้นสำหรับฐานข้อมูล

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

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

Preparing Video For Download...