四十七:数据库之alembic数据库迁移工具的基本使用

在一般情况下,如果修改了模型,如增加或者删除了字段,SQLAlchemy是不会更新的,这就需要使用alembic来实现

使用alembic步骤:
一:定义好模型
二:使用alembic创建一个仓库:alembic init 仓库名
三:修改配置文件
1、在alembic.ini中,给SQLAlchemy.url设置数据库的连接方式,这个连接方式与SQLAlchemy的方式一样
2、在alembic/env.py中的target_metadata设置模型的Base.metadata,前提是要导入Base.metadata
四:将ORM模型生成迁移脚本:alembic revision --autogenerate -m ‘message‘
五:将生成的脚本映射到数据库中:alembic upgrade head
六:以后如果修改了模型,重复4/5步骤
七:想要使用alembic命令,需要进入到安装了alembic的虚拟环境中,不然就无法使用

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用

在命令行,激活虚拟环境

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用

修改配置文件

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用

alembic revision --autogenerate -m ‘first_commit‘

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用

alembic upgrade head

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用

添加字段

四十七:数据库之alembic数据库迁移工具的基本使用

alembic revision --autogenerate -m ‘add_age_colunm‘

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用

alembic upgrade head

四十七:数据库之alembic数据库迁移工具的基本使用

四十七:数据库之alembic数据库迁移工具的基本使用