MySQL在NOT NULL列中插入具有NULL值的记录 [英] MySQL Inserts record with NULL value in NOT NULL column

查看:138
本文介绍了MySQL在NOT NULL列中插入具有NULL值的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一个INSERT要通过table2.请注意,table2.col_1不为NULL.它不会为col_1插入NULL,而是神秘地将NULL值转换为空字符串.我正在使用MySQL版本5.5.28.谢谢

Why does the first INSERT go through for table2. Note that table2.col_1 is NOT NULL. It doesn't insert NULL for col_1, but mysteriously converts the NULL value to an empty string. I am using MySQL Version 5.5.28. Thanks

mysql> DROP TABLE IF EXISTS table1, table2;

Query OK, 0 rows affected (0.01 sec)   

mysql> CREATE  TABLE IF NOT EXISTS table1 (
    -> id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
    -> col_1 VARCHAR(45) NOT NULL ,
    -> col_2 VARCHAR(45) NOT NULL ,
    -> PRIMARY KEY (`id`))
    -> ENGINE = InnoDB;

Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE table2 LIKE table1;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO table1 (id, col_1, col_2) VALUES (NULL, "xxx","yyy");
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO table2 (id, col_1, col_2) SELECT NULL, NULL, col_2 FROM table1 WHERE id=1;
Query OK, 1 row affected, 1 warning (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 1

mysql> SHOW WARNINGS;
+---------+------+-------------------------------+
| Level   | Code | Message                       |
+---------+------+-------------------------------+
| Warning | 1048 | Column 'col_1' cannot be null |
+---------+------+-------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM table2;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
|  1 |       | yyy   |
+----+-------+-------+
1 row in set (0.00 sec)

mysql> INSERT INTO table2 (id, col_1, col_2) VALUES( NULL, NULL, "zzz");
ERROR 1048 (23000): Column 'col_1' cannot be null

mysql> SELECT * FROM table2;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
|  1 |       | yyy   |
+----+-------+-------+
1 row in set (0.00 sec)

推荐答案

您已将MySQL的STRICT模式设置为OFF. 打开它,您会得到一个错误.

You have MySQL's STRICT mode OFF. Turn it on and you'll get an error.

否则,您可以通过以下方式使用PDO测试这些警告: http://php.net /manual/en/pdo.errorinfo.php

Otherwise you can test for those warnings with PDO via: http://php.net/manual/en/pdo.errorinfo.php

这篇关于MySQL在NOT NULL列中插入具有NULL值的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆