检查 int 变量是否为 null 或者数据库中为空
我有一个变量:
nocustomers = rs.getInt("CUST_TRAN_COUNT");
如果它是否为空,我想执行。
我尝试了
if (nocustomers ==null)
一下,显示错误。
我该如何解决这个问题?
我新修改的代码是:
try{
query=" select * from SS_summary where txn_date = to_date ('"+asatdate+"','YYYY-MM-DD') ";
st = conn.createStatement();
rs = st.executeQuery(query);
if (rs.next())
{
nocustomers = rs.getInt("CUST_TRAN_COUNT");
nocheques =rs.getInt("CHEQ_DELIVERED_MAIN");
}
if (rs.wasNull()) {
out.println("NO DATA FOUND");
}
%>
I am having a variable which is:
nocustomers = rs.getInt("CUST_TRAN_COUNT");
I would like to perform if it is null or not.
I tried
if (nocustomers ==null)
It showed an error.
How do I solve this?
My new modified code is:
try{
query=" select * from SS_summary where txn_date = to_date ('"+asatdate+"','YYYY-MM-DD') ";
st = conn.createStatement();
rs = st.executeQuery(query);
if (rs.next())
{
nocustomers = rs.getInt("CUST_TRAN_COUNT");
nocheques =rs.getInt("CHEQ_DELIVERED_MAIN");
}
if (rs.wasNull()) {
out.println("NO DATA FOUND");
}
%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
int
不能为null
,因为它是原始类型。出于同样的原因
ResultSet.getInt()
无法返回null
。您需要调用
ResultSet.wasNull( )
在您的getInt()
调用之后检查该值是否为null
。请注意,由于
int
不能为null
,因此即使数据库值为null
,nocustomer
也会有一个值。getInt()
定义为当 DB 值为null
时返回0
,因此nocustomers
将为0 。
int
can't benull
, because it's a primitive type.For the same reason
ResultSet.getInt()
can't returnnull
.You will need to call
ResultSet.wasNull()
right after yourgetInt()
call to check if the value wasnull
.Note that since
int
can't benull
,nocustomer
will have a value even if the database value isnull
.getInt()
is defined to return0
when the DB value isnull
, sonocustomers
will be0
.在编译时,java 编译器将抱怨以下消息:
那是因为您永远不能对原始类型进行空检查。基本类型分配有默认值(零,对于整数),如果未分配。
如果您想知道读取的值是否为空,请使用
ResultSet.wasNull()
方法(读取整数值后,请参阅提供的 JavaDoc 链接):At compile time, the java compiler will complain with the following message:
That is because you can never do a null check on primitive types. Primitive types are assigned with default values (zero, for integers), if unassigned.
If you want to know if the value read was null, use the
ResultSet.wasNull()
method instead (after reading your integer value, see JavaDoc link provided):如果值为
NULL
,则getInt
将返回0,然后您可以调用wasNull
来检查它是否包含0或如果它是一个NULL
。另请参阅:wasNull()< /a>
If the value was
NULL
, then 0 will be returned bygetInt
, and then you could callwasNull
to check if it held a 0 or if it was aNULL
.See also: wasNull()
你可以使用,
但在某些情况下(非常罕见),一旦你调用了 getObject,你就不能调用 getInt,在这种情况下你可以简单地使用
另外,我认为更好的方法是,
所以如果数据库返回 null, value 将为 0,但 nullValue 将为 true,以便您可以执行所需的操作
you can use,
but in some cases (very rare) you can't call the getInt once you called the getObject, in that case you can simply use
Also, I think better way to do it is,
so if the db returned null, value would be 0 however nullValue will be true so that you can do the needful
有一个
wasNull
方法:ResultSet
或RowSet
上的There is a
wasNull
method on yourResultSet
orRowSet
: