MySQL中CURRENT_TIMESTAMP的使用方式

目录
  • current_timestamp的使用
  • timestamp使用current_timestamp报错

current_timestamp的使用

众所周知,mysql的日期类型可以使用current_timestamp来指定默认值,但是这个跟mysql的版本及日期的具体类型有关,只有5.6之后的版本才能使用current_timestamp作为datetime的默认值。

例如:

alter table t_user add update_time datetime default current_timestamp

在5.6之前的版本,使用current_timestamp作为默认值时,就会出现下面的错误

[err] 1067 – invalid default value for ‘update_time’

在mysql 5.6.5版本之前,default current_timestamp on update current_timestamp只适用于timestamp,而且一张表中,最多允许一个timestamp字段采用该特性。 从mysql 5.6.5开始, default current_timestamp on update current_timestamp同时适用于timestamp和datetime,且不限制数量。

timestamp使用current_timestamp报错

项目出现如下错误:

error updating database.

cause:com.mysql.jdbc.exceptions.jdbc4.mysqlintegrityconstraintviolationexception: column ‘createtime’ cannot be null

数据模型如下:

  /* 创建时间不可为空*/
  createtime timestamp not null default current_timestamp comment '创建时间' ,
  /* 更新时间不可为空*/
  updatetime timestamp not null default current_timestamp on update current_timestamp comment '更新时间' ,

经过一系列的问题排查,定位到是因为不同版本的mysql数据库全局变量“explicit_defaults_for_timestamp”的问题。

-- 查看explicit_defaults_for_timestamp默认值
show global variables like "explicit_defaults_for_timestamp"; 

-- 修改explicit_defaults_for_timestamp默认值
set @@global.explicit_defaults_for_timestamp=off;

参数值为”on”的情况:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐