解决查询数据库int类型为空时的报错问题
1.数据库数据
表:student
名 | 类型 |
---|---|
id | int |
name | varchar |
age | int |
2.查询年龄
SELECT age FROM student where id=5;
报错原因可能有两个:
(1)age为null
(2)id=5的数据为空,即不存在该条数据
解决方法
1.当age为空时赋值一个默认值
SELECT IFNULL(age ,-1) as age FROM student where id=5;
但是这样还有一个问题:当该条数据不存在时还是会报异常,因为IFNULL()判断的只是age的列信息
进一步的解决方法:
SELECT IFNULL(MAX(age),-1) as age FROM student where id=5;
这样虽然可以解决报错的问题,但是无法知道是因为age为null还是数据不存在。
想要解决这个问题,加多一个查询信息:
SELECT COUNT(1) as isExit, IFNULL(age ,-1) as age FROM student where id=5;
判断数据否存在,就可以很好地解决上述问题。