创建数据库

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...