一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

mysql时间字段默认设置为当前时间代码实例

时间:2022-08-08 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下mysql时间字段默认设置为当前时间代码实例,对大家的学习有一定的帮助,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

mysql时间字段默认为当前时间

1、直接在创建表时添加该列并声明默认值,如下:

CREATE TABLE `table1` (
  `id` int(11) NOT NULL,
  `createtime` timestamp NULL default CURRENT_TIMESTAMP,
  `updatetime` timestamp NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

如果是在navicat下操作的话,设置字段的类型为timestamp,默认值写上CURRENT_TIMESTAMP,如下图:

2、在现有表中添加新列

ALTER TABLE table1
ADD COLUMN  `createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP

3、 修改某一列为时间格式并添加默认值

alter table table1 
 change createtime newtime timestamp null default current_timestamp

4、展示毫秒

如果想记录到毫秒,设置CURRENT_TIMESTAMP(3)即可

附:mysql 字段 default 默认赋值 当前系统时间

建表代码如下:

create table B_Data(
Id int PRIMARY key auto_increment,
Position VARCHAR(200) not null DEFAULT '',
CorporateName VARCHAR(500) not null DEFAULT '',
WorkingPlace VARCHAR(1000) not NULL DEFAULT '',
Salary  VARCHAR(200) not null DEFAULT '',
ReleaseTime VARCHAR(300) not null DEFAULT '',
DataTime  timestamp not NULL default CURRENT_TIMESTAMP 
)

其中因为 mysql 不像 sql 一样可以直接使用函数获取,因此字段类型 timestamp 与 datetime 相同,

所以完整的代码如下:

DataTime  timestamp not NULL default CURRENT_TIMESTAMP 

以上内容属于自己的笔记,避免忘记 ,初学 mysql 多多指教

查看表结构代码:

show columns from B_Data

热门栏目