专题描述 | 解释explicit_defaults_for_timestamp参数的含义和explicit_defaults_for_timestamp参数 值设定对插入NULL值的影响 | |||
问题提出 | OMS系统测试时出现插入数据报错的问题: 时间字段无法写入值(下单): b2c1 10.202.198.200:3319 oms1/oms1 b2c2 10.202.198.201:3319 oms2/oms2 b2c3 10.202.198.202:3319 oms3/oms3 b2c4 10.202.198.203:3319 oms4/oms4 后续报错省略。 | |||
分析过程 | 1 | 关于定义字段为NOT NULL,插入NULL值不成功的问题与sql_mode参数的设置没有关系。 在MySQL中设置参数explicit_defaults_for_timestamp=off的情况下, 对于timestamp 类型列定义为not null属性的情况下,插入null值不报错, 但MySQL会将null值处理为当前时间。 举例说明: 对于timestamp类型列定义为not null,没有default值的情况: root@localhost : test 06:17:02> show variables like 'explicit_defaults_for_timestamp'; +---------------------------------+-------+| Variable_name | Value | +---------------------------------+-------+ | explicit_defaults_for_timestamp | OFF | +---------------------------------+-------+ 1 row in set (0.01 sec) | ||
test 06:21:33> show create table t; | Table | Create Table | t | CREATE TABLE `t` ( `id` int(11) DEFAULT NULL, `t1` timestamp NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | 1 row in set (0.00 sec) | ||||
insert into t values(1,null); Query OK, 1 row affected (0.03 sec) root@localhost : test 06:22:20> select * from t; +------+---------------------+ | id | t1 | +------+---------------------+ | 1 | 2015-06-23 18:22:20 | +------+---------------------+ 1 row in set (0.00 sec) | ||||
对于定义timestamp类型列 not null,有default值的情况: root@localhost : test 06:31:16> show variables like 'explicit_defaults_for_timestamp'; +---------------------------------+-------+| Variable_name | Value | +---------------------------------+-------+ | explicit_defaults_for_timestamp | OFF | +---------------------------------+-------+ 1 row in set (0.00 sec) | ||||
test 06:31:22> show create table tt; | Table | Create Table | | tt | CREATE TABLE `tt` ( `id` int(11) DEFAULT NULL, `t1` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | 1 row in set (0.00 sec) | ||||
test 06:31:29> insert into tt values(1,null); Query OK, 1 row affected (0.00 sec) root@localhost : test 06:31:35> select * from tt; +------+---------------------+ | id | t1 | +------+---------------------+ | 1 | 2015-06-23 18:31:35 | +------+---------------------+ 1 row in set (0.01 sec) | ||||
解决方案 | explicit_defaults_for_timestamp=off参数仅对于timestamp类型的列有效 ,其它数据类型的列定义为not null时, 不要插入null值。 | |||
问题原因 | explicit_defaults_for_timestamp=off参数仅对于timestamp类型的列有效 ,其它类型的列定义为not null, 是无法插入null值。 | |||
知识点 | explicit_defaults_for_timestamp = off值时 ,向定义为timestamp NOT NULL的列值中插入NULL值时允许的,且插入值为插入语句当前时间。 当explicit_defaults_for_timestamp = ON值时, 不可向timestamp NOT NULL列中插入NULL值。 |
转载于:https://blog.51cto.com/yixianwei/1902835