如何处理 PreparedStatement 中的(可能)空值? [英] How to deal with (maybe) null values in a PreparedStatement?
本文介绍了如何处理 PreparedStatement 中的(可能)空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
声明是
SELECT * FROM tableA WHERE x = ?
并且参数是通过 java.sql.PreparedStatement 'stmt' 插入的
and the parameter is inserted via java.sql.PreparedStatement 'stmt'
stmt.setString(1, y); // y may be null
如果 y
为 null,则该语句在任何情况下都不返回任何行,因为 x = null
始终为 false(应为 x IS NULL
).一种解决方案是
If y
is null, the statement returns no rows in every case because x = null
is always false (should be x IS NULL
).
One solution would be
SELECT * FROM tableA WHERE x = ? OR (x IS NULL AND ? IS NULL)
但是我必须两次设置相同的参数.有没有更好的解决方案?
But then i have to set the same parameter twice. Is there a better solution?
谢谢!
推荐答案
我一直都是按照你在问题中展示的方式来做的.两次设置相同的参数不是一个巨大的困难,是吗?
I've always done it the way you show in your question. Setting the same parameter twice is not such a huge hardship, is it?
SELECT * FROM tableA WHERE x = ? OR (x IS NULL AND ? IS NULL);
这篇关于如何处理 PreparedStatement 中的(可能)空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文