如何处理PreparedStatement中的(可能)空值? [英] How to deal with (maybe) null values in a PreparedStatement?

查看:257
本文介绍了如何处理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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆