建立資料庫與資料表

Python 資料庫入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

建立資料庫

  • 依資料庫類型而異
  • 像 PostgreSQL、MySQL 可用命令列工具初始化資料庫
  • 對 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 物件,如同反射時一樣
  • 以 Column 物件取代 autoload 參數
  • 對 MetaData 執行 create_all(),在實際資料庫中建立資料表
  • 資料表更新需用其他工具,如 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...