MySQL在NOT NULL列中插入带NULL值的记录

时间:2013-04-09 14:58:54

标签: mysql

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

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)

3 个答案:

答案 0 :(得分:9)

你有MySQL的STRICT模式关闭。 打开它会导致错误。

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

答案 1 :(得分:5)

这种行为在MySQL文档中有详细记载。 MySQL doc

如果您没有使用严格模式,那么无论何时向列中插入“不正确”值,such as a NULL into a NOT NULL column或数字列中的数字值过大,MySQL都会将列设置为“最佳”值“而不是产生错误:,但警告计数增加

答案 2 :(得分:-1)

我尝试将MySQL的STRICT模式设置为OFF并且对我不起作用(我甚至将其更改为“my.ini”)。

对我有用的是BEFORE INSERT TRIGGER

基本上你这样做:

CREATE TRIGGER triggerName BEFORE INSERT ON customer
FOR EACH ROW
BEGIN
    if new.`customerName` = '' then
    signal sqlstate '45000'
    SET MESSAGE_TEXT = 'Customer Name Cannot be Empty!';
    end if;
END

MESSAGE_TEXT中,您可以添加要显示错误的任何文字。

希望它有所帮助!

其中大部分都找到here

相关问题