Welcome everyone

insert into的一个小坑

mysql 汪明鑫 391浏览 0评论

有同学在一次代码调整中,mysql “insert ignore into” 错误改为 “insert into”,导致线上问题

insert ignore into 印象中我们通常用来处理uk重复插入异常,还有另一个坑,会导致插入失败

我们创建一个表:

mysql> create table test(id int not null);
Query OK, 0 rows affected (0.07 sec)

插入语句:

mysql> insert into test (id) values(1)
    -> ;
Query OK, 1 row affected (0.02 sec)

再批量写入一些

mysql> insert into test (id) values(5),(6);
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

假如我们批量写入的值有null, 会报错

mysql> insert into test (id) values(8),(null),(10);
ERROR 1048 (23000): Column 'id' cannot be null

我们用 insert ignore into 又会成功写入

mysql> insert ignore into test (id) values(8),(null),(10);
Query OK, 3 rows affected, 1 warning (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 1

这里会自动把“null”转为“0”

mysql> select * from test;
+----+
| id |
+----+
|  1 |
|  5 |
|  6 |
|  8 |
|  0 |
| 10 |
+----+
6 rows in set (0.00 sec)

此时如果错误的把 “ignore” 删掉,就可能会导致插入异常

测试环境一般不会构建null值测试,因此线下测试也不好发现,但线上的异常case会触发这个问题,导致失败。

再构建DO对象的时候,尽量规避null值,可以用 org.apache.commons.lang3.ObjectUtils 中的

defaultIfNull 为空对象赋默认值。
遇到 "insert ignore into" 的sql 不要大胆的改成 "insert into"。。

转载请注明:汪明鑫的个人博客 » insert into的一个小坑

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz