找到mysql安装目录下的my.cnf(windows系统则是my.ini)文件
在sql_mode中加入STRICT_TRANS_TABLES则表示开启严格模式,如没有加入则表示非严格模式,修改后重启mysql即可
例如这就表示开启了严格模式:
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
创建数据表方便测试
CREATE TABLE `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入一条记录,name的值为null
在非严格模式下执行
mysql> insert into mytable(content) values('programmer');
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> select * from mytable;
+----+------+------------+
| id | name | content |
+----+------+------------+
| 1 | | programmer |
+----+------+------------+
1 row in set (0.00 sec)
执行成功,name的值自动转为”
在严格模式下执行
mysql> insert into mytable(content) values('programmer');
ERROR 1364 (HY000): Field 'name' doesn't have a default value
执行失败,提示字段name不能为null值
对id字段插入”值
在非严格模式下执行
mysql> insert into mytable(id,name,content) value('','fdipzone','programmer');
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> select * from mytable;
+----+----------+------------+
| id | name | content |
+----+----------+------------+
| 1 | fdipzone | programmer |
+----+----------+------------+
1 row in set (0.00 sec)
执行成功
在严格模式下执行
mysql> insert into mytable(id,name,content) value('','fdipzone','programmer');
ERROR 1366 (HY000): Incorrect integer value: '' for column 'id' at row 1
执行失败,提示字段id不能为”
mysql> insert into mytable(id,name,content) value(null,'fdipzone','programmer');
Query OK, 1 row affected (0.00 sec)
mysql> select * from mytable;
+----+----------+------------+
| id | name | content |
+----+----------+------------+
| 1 | fdipzone | programmer |
+----+----------+------------+
1 row in set (0.00 sec)
字段id为null则可执行成功
创建一个数据表mytable,其中text设置默认值default=”
在非严格模式下执行
mysql> CREATE TABLE `mytable` (
-> `id` int(11) NOT NULL AUTO_INCREMENT,
-> `name` varchar(20) NOT NULL,
-> `content` text NOT NULL default '',
-> PRIMARY KEY (`id`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected, 1 warning (0.03 sec)
mysql> show tables;
+------------------------------+
| Tables_in_test_version |
+------------------------------+
| mytable |
+------------------------------+
执行成功
在严格模式下执行
mysql> CREATE TABLE `mytable` (
-> `id` int(11) NOT NULL AUTO_INCREMENT,
-> `name` varchar(20) NOT NULL,
-> `content` text NOT NULL default '',
-> PRIMARY KEY (`id`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ERROR 1101 (42000): BLOB/TEXT column 'content' can't have a default value
执行失败,提示content字段是TEXT类型,不能使用默认值。
总结,使用mysql严格模式可以使数据更加安全严格,缺点是减少了对空数据入库的兼容性。建议开发环境使用严格模式以提高代码的质量及对数据的严谨性。