#配置deovoice mysql设置时间戳自动获取当前时间 | blog of coderdz

mysql设置时间戳自动获取当前时间

应用场景

  1. 在数据表中,记录每条数据是什么时候创建的,不需要应用程序特意去记录,由数据库获取当前时间自动创建时间;
  2. 在数据库中,要记录每条数据是什么时候修改的,不需要应用程序特意记录,而是由书库获取当前时间自动记录修改时间;

实现方式

  1. 将字段类型设置为 timestamp
  2. 将默认值设置为 current_timestamp

For example:

  1. 添加create_time字段
    alter table 'table_name' add column 'create_time' datetime null default current_timestamp comment '创建时间';
  2. 修改create_time字段(modify)
    alter table 'table_name' modify column 'create_time' datetime null default current_timestamp comment '创建时间';
  3. 添加update_time字段
    alter table 'table_name' add column 'update_time' timestamp null default current_timestamp on update current_timestamp comment '创建时间';
  4. 修改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等等,也是很方便。

谢谢你请我吃苹果!
-------------本文结束感谢您的阅读-------------