应用场景
- 在数据表中,记录每条数据是什么时候创建的,不需要应用程序特意去记录,由数据库获取当前时间自动创建时间;
- 在数据库中,要记录每条数据是什么时候修改的,不需要应用程序特意记录,而是由书库获取当前时间自动记录修改时间;
实现方式
- 将字段类型设置为 timestamp
- 将默认值设置为 current_timestamp
For example:
- 添加create_time字段
alter table 'table_name' add column 'create_time' datetime null default current_timestamp comment '创建时间';
- 修改create_time字段(modify)
alter table 'table_name' modify column 'create_time' datetime null default current_timestamp comment '创建时间';
- 添加update_time字段
alter table 'table_name' add column 'update_time' timestamp null default current_timestamp on update current_timestamp comment '创建时间';
- 修改update_time字段(modify)
alter table 'table_name' modify column 'update_time' timestamp null default current_timestamp on update current_timestamp comment '创建时间';
当然,上面说的是基于命令行的操作,通过sql语句实现的。用MySQL可视化工具也是可以直接设置的,如phpMyAdmin,navicat等等,也是很方便。