数据库教程:mysql 实现添加时间自动添加更新时间自动更新操作

在数据库使用中经常使用到时间字段。常用的有创建时间和更新时间。然而在使用中想要创建时间在创建的时候自动设置为当前时间,更新时间在更新时自动更新为当前时间。创建表 stucreate table `st

在数据库使用中经常使用到时间字段。常用的有创建时间和更新时间。

然而在使用中想要创建时间在创建的时候自动设置为当前时间,更新时间在更新时自动更新为当前时间。

创建表 stu

  create table `stu` (  'id' int not null auto_increment,  'createtime' timestamp default current_timestamp comment '创建时间',  'moditiytime' timestamp default current_timestamp on update current_timestamp comment '更新时间',  primary key ('id'));

创建的时候设置当前时间

  default current_timestamp

更新的时候设置更新时间为当前时间

  default current_timestamp on update current_timestamp

补充:mysql为字段添加默认时间(插入时间)

应用场景:

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

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

实现方式:

1、将字段类型设为 timestamp

2、将默认值设为 current_timestamp

举例应用:

1、mysql 脚本实现用例

–添加createtime 设置默认时间 current_timestamp

  alter table table_name  add column createtime datetime null default current_timestamp comment ‘创建时间' ;

–修改createtime 设置默认时间 current_timestamp

  alter table table_name  modify column createtime datetime null default current_timestamp comment ‘创建时间' ;

–添加updatetime 设置 默认时间 current_timestamp 设置更新时间为 on update current_timestamp

  alter table table_name  add column updatetime timestamp null default current_timestamp on update current_timestamp comment ‘创建时间' ;

–修改 updatetime 设置 默认时间 current_timestamp 设置更新时间为 on update current_timestamp

  alter table table_name  modify column updatetime timestamp null default current_timestamp on update current_timestamp comment ‘创建时间' ;

2、mysql工具设置

mysql 实现添加时间自动添加更新时间自动更新操作

mysql自动管理,保持和数据库时间一致性。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持<计算机技术网(www.ctvol.com)!!>。如有错误或未考虑完全的地方,望不吝赐教。

需要了解更多数据库技术:mysql 实现添加时间自动添加更新时间自动更新操作,都可以关注数据库技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/dtteaching/809833.html

(0)
上一篇 2021年9月11日
下一篇 2021年9月11日

精彩推荐