explicit_defaults_for_timestamp使用

67 阅读2分钟

前言

explicit_defaults_for_timestamp系统变量决定MySQL服务端对timestamp列中的默认值和NULL值的不同处理方法

explicit_defaults_for_timestamp使用

变量解释

MySQL5.7以下版本中,这个系统变量默认是关闭的,可以利用以下语句查询该系统变量处理打开还是关闭

show global VARIABLES like 'explicit_defaults_for_timestamp%';

image.png 这里使用的是MySQL5.7版本

image.png

Off状态

1、 新建一张新表

-- ----------------------------
-- Table structure for device
-- ----------------------------
DROP TABLE IF EXISTS `sys_device`;
CREATE TABLE `sys_device`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `deviceName` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自定义设备名称',
  `createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 96713335083012 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '设备' ROW_FORMAT = DYNAMIC;

2、 执行以下语句

insert into sys_device (id, deviceName, createTime) VALUES (1, 'aaaa' ,NULL);

结果如下图

image.png 时间会以当前时间为准

3、 执行以下语句

insert into sys_device (id, deviceName) VALUES (2, 'aaaa2');

结果如下图 image.png 时间戳还是以当前为准

ON状态

1、执行以下语句,打开状态

SET @@GLOBAL.explicit_defaults_for_timestamp = 'ON';

2、查询explicit_defaults_for_timestamp当前状态

image.png

3、将上述数据清除,然后执行以下语句

insert into sys_device (id, deviceName) VALUES (1, 'aaaa2');

结果如下图 image.png 如果strict sql_mode没被指定了,那么可以继续插入,如果指定了,就直接报错

4、以MySQL8数据库版本为准,该版本以上的数据库默认是开启的

image.png

image.png

5、执行以下语句会报错

insert into sys_device (id, deviceName, createTime, updateTime) VALUES (3, 'aaaa3', null, null);

image.png

总结

当explicit_defaults_for_timestamp=OFF时,即使timestamp列设为NOT NULL也能插入NULL值,系统会自动将NULL值设为current timestamp,当开启了Strict Mode时,插入会报错,可以设置关掉