Tạo cơ sở dữ liệu và bảng

Nhập môn Cơ sở dữ liệu với Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Tạo cơ sở dữ liệu

  • Phụ thuộc vào loại cơ sở dữ liệu
  • PostgreSQL, MySQL có công cụ dòng lệnh để khởi tạo DB
  • Với SQLite, câu lệnh create_engine() sẽ tạo DB và tệp nếu chưa tồn tại
Nhập môn Cơ sở dữ liệu với Python

Tạo một bảng

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']
Nhập môn Cơ sở dữ liệu với Python

Tạo bảng

  • Vẫn dùng đối tượng Table như khi phản chiếu
  • Thay autoload bằng các đối tượng Column
  • Tạo bảng trong DB thực bằng create_all() trên MetaData
  • Cần công cụ khác để cập nhật bảng, như Alembic hoặc SQL thuần
Nhập môn Cơ sở dữ liệu với Python

Tạo bảng - tùy chọn cột bổ sung

  • unique bắt buộc giá trị trong cột là duy nhất
  • nullable xác định cột có thể trống trong một hàng hay không
  • default đặt giá trị mặc định nếu không cung cấp.
Nhập môn Cơ sở dữ liệu với Python

Tạo bảng với tùy chọn bổ sung

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))}
Nhập môn Cơ sở dữ liệu với Python

Ayo berlatih!

Nhập môn Cơ sở dữ liệu với Python

Preparing Video For Download...