mysql数据库自动添加创建时间及更新时间

2022-10-22,,,,

前言

志在巅峰的攀登者,不会陶醉在沿途的某个脚印之中,在码农的世界里,优美的应用体验,来源于程序员对细节的处理以及自我要求的境界,年轻人也是忙忙碌碌的码农中一员,每天、每周,都会留下一些脚印,就是这些创作的内容,有一种执着,就是不知为什么,如果你迷茫,不妨来瞅瞅码农的轨迹。

1、描述

在mysql中,添加表中的列类型为时间类型(timestamp)时,可设置默认值

设置时间列的默认值为自动获取创建时间:

default current_timestamp

设置时间列的默认值为自动获取更新时间

 default current_timestamp on update current_timestamp

再添加个值不可为null

#创建时间
not null default current_timestamp
# 更新时间
not null default current_timestamp on update current_timestamp

2 完整的操作 sql

2.1 修改现有表中的时间列默认值为自动获取

修改表 t_user 中的 create_time 列 在插入新的数据时 如果值为空就设置为当前的系统时间

#修改表 t_user 中的 create_time 列 在插入新的数据时 如果值为空就设置为当前的系统时间
alter table t_user modify create_time timestamp not null default current_timestamp comment '创建时间';

修改表 t_user 中的 update_time 列 在修改的数据时 如果值为空就设置为当前的系统时间

#修改表 t_user 中的 update_time 列 在修改的数据时 如果值为空就设置为当前的系统时间
alter table t_user modify update_time timestamp not null default current_timestamp on update current_timestamp comment '更新时间';

2.2 现有表中添加时间列设置默认值

新增表 t_user 中的 create_time 列

#新增表 t_user 中的 create_time 列 
 alter table t_user add create_time timestamp not null default current_timestamp comment '创建时间';

新增表 t_user 中的 update_time 列

 #新增表 t_user 中的 update_time 列 
 alter table t_user add update_time timestamp not null default current_timestamp on update current_timestamp comment '更新时间';

2.3 创建表时时间列设置默认值

create table t_user(
  id integer not null auto_increment primary key,
  user_name varchar(20) not null ,
  update_time timestamp  default current_timestamp on update current_timestamp comment '更新时间',
    create_time timestamp  default current_timestamp comment '创建时间'
);

总结

到此这篇关于mysql数据库自动添加创建时间及更新时间的文章就介绍到这了,更多相关mysql自动添加创建更新时间内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《mysql数据库自动添加创建时间及更新时间.doc》

下载本文的Word格式文档,以方便收藏与打印。