码迷,mamicode.com
首页 > 数据库 > 详细

MySQL timestamp NOT NULL插入NULL的问题

时间:2016-05-26 14:51:16      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:explicit_defaults_for_timestamp


explicit_defaults_for_timestamp


MySQL 5.6版本引入

explicit_defaults_for_timestamp

来控制对timestamp NULL值的处理

 

如果该参数不开启,则对timestamp NOT NULL插入NULL值,不报错,无warning,插入后的值为当前时间

如果在my.cnf中explicit_defaults_for_timestamp=1

那么插入该值的时候会报错提示该列can not be null

建议开启该值

mysql> show variables like ‘%explicit_defaults_for_timestamp%‘;
+---------------------------------+-------+
| Variable_name                   | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | OFF   |
+---------------------------------+-------+
1 row in set (0.00 sec)


mysql> show create table helei\G
*************************** 1. row ***************************
       Table: helei
Create Table: CREATE TABLE `helei` (
  `a` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.08 sec)

mysql> select * from helei;
Empty set (0.03 sec)

mysql> insert into helei values(NULL);
Query OK, 1 row affected (0.39 sec)

mysql> select * from helei;
+---------------------+
| a                   |
+---------------------+
| 2016-05-26 11:44:24 |
+---------------------+
1 row in set (0.03 sec)

可以看到

explicit_defaults_for_timestamp

插入的NULL值变为当前时间,并没有被NOT NULL所限制


且该值是无法动态修改的,必须重启库才可以变更

mysql> set global explicit_defaults_for_timestamp=0;

ERROR 1238 (HY000): Variable ‘explicit_defaults_for_timestamp‘ is a read only variable



我们在my.cnf并重启库后,可以看到null值已经不被允许插入了

mysql> select * from helei;
+---------------------+
| a                   |
+---------------------+
| 2016-05-26 11:44:24 |
| 2016-05-26 11:45:46 |
+---------------------+
2 rows in set (0.00 sec)

mysql> insert into helei values(null);
ERROR 1048 (23000): Column ‘a‘ cannot be null

mysql> insert into helei values(NULL);
ERROR 1048 (23000): Column ‘a‘ cannot be null


本文出自 “岁伏” 博客,请务必保留此出处http://suifu.blog.51cto.com/9167728/1783400

MySQL timestamp NOT NULL插入NULL的问题

标签:explicit_defaults_for_timestamp

原文地址:http://suifu.blog.51cto.com/9167728/1783400

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!