一、sql_mode模式
mysql数据库的中有一个环境变量sql_mode,定义了mysql应该支持的sql语法,数据校验等!
1.查看sql_mode。
mysql> select @@sql_mode;
mysql> show variables like ‘sql_mode%’\G;
2.模式区别。
mysql5.0以上版本支持三种sql_mode模式:ANSI、TRADITIONAL和STRICT_TRANS_TABLES。
ANSI模式:宽松模式,对插入数据进行校验,如果不符合定义类型或长度,对数据类型调整或截断保存,报warning警告。
TRADITIONAL模式:严格模式,当向mysql数据库插入数据时,进行数据的严格校验,保证错误数据不能插入,报error错误。用于事物时,会进行事物的回滚。
STRICT_TRANS_TABLES模式:严格模式,进行数据的严格校验,错误数据不能插入,报error错误。
a.ANSI模式。
1. mysql> set @@sql_mode=ANSI;
2. Query OK, 0 rows affected (0.00 sec)
3.
4. mysql> create table test(name varchar(4), pass varchar(4));
5. Query OK, 0 rows affected (0.03 sec)
6.
7. mysql> insert into test values('aaaaa','aaaaa'),('bbbb','bbbb');
8. Query OK, 2 rows affected, 2 warnings (0.02 sec)
9. Records: 2 Duplicates: 0 Warnings: 2
10.
11. mysql> show warnings;
12. +---------+------+-------------------------------------------+
13. | Level | Code | Message |
14. +---------+------+-------------------------------------------+
15. | Warning | 1265 | Data truncated for column 'name' at row 1 |
16. | Warning | 1265 | Data truncated for column 'pass' at row 1 |
17. +---------+------+-------------------------------------------+
18. 2 rows in set (0.00 sec)
19.
20. mysql> select * from test;
21. +------+------+
22. | name | pass |
23. +------+------+
24. | aaaa | aaaa |
25. | bbbb | bbbb |
26. +------+------+
27. 2 rows in set (0.00 sec)
b.TRADITIONAL模式
1. mysql> set @@sql_mode=TRADITIONAL;
2. Query OK, 0 rows affected (0.00 sec)
3.
4. mysql> create table test(name varchar(4), pass varchar(4));
5. Query OK, 0 rows affected (0.02 sec)
6.
7. mysql> insert into test values('aaaaa','aaaaa'),('bbbb','bbbb');
8. ERROR 1406 (22001): Data too long for column 'name' at row 1
9.
10. mysql> show errors;
11. +-------+------+------------------------------------------+
12. | Level | Code | Message |
13. +-------+------+------------------------------------------+
14. | Error | 1406 | Data too long for column 'name' at row 1 |
15. +-------+------+------------------------------------------+
16. 1 row in set (0.00 sec)
17.
18. mysql> select * from test;
19. Empty set (0.00 sec)
c.STRICT_TRANS_TABLES模式
1. mysql> set @@sql_mode=STRICT_TRANS_TABLES;
2. Query OK, 0 rows affected (0.00 sec)
3.
4. mysql> create table test(name varchar(4), pass varchar(4));
5. Query OK, 0 rows affected (0.02 sec)
6.
7. mysql> insert into test values('aaaaa','aaaaa'),('bbbb','bbbb');
8. ERROR 1406 (22001): Data too long for column 'name' at row 1
9.
10. mysql> show errors;
11. +-------+------+------------------------------------------+
12. | Level | Code | Message |
13. +-------+------+------------------------------------------+
14. | Error | 1406 | Data too long for column 'name' at row 1 |
15. +-------+------+------------------------------------------+
16. 1 row in set (0.00 sec)
17.
18. mysql> select * from test;
19. Empty set (0.00 sec)
3.修改配置文件。
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES