Check variable int null or empty from database

I have a variable that:

nocustomers = rs.getInt("CUST_TRAN_COUNT"); 

I would like to execute if it is null or not.

I tried

 if (nocustomers ==null) 

He showed a mistake.

How to solve this?


My new modified code:

 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"); } %> 
+7
source share
5 answers

int cannot be null because it is a primitive type.

For the same reason, ResultSet.getInt() cannot return null .

You will need to call ResultSet.wasNull() right after your getInt() call to check if it was null .

Note that since an int cannot be null , the nocustomer will be even if the database value is null . getInt() defined as return 0 when the DB value is null , so nocustomers will be 0 .

+6
source

During compilation, the java compiler will complain about the following message:

 incomparable types: int and <nulltype> if (nocustomers == null) { ^ 

This is because you can never perform null checking on primitive types. Primitive types are assigned default values ​​(zero, for integers) , if not assigned.

If you want to know if a value was considered zero, use ResultSet.wasNull() ( after reading your integer value, see the JavaDoc link):

 nocustomers = rs.getInt("CUST_TRAN_COUNT"); if (rs.wasNull()) { nocustomers = -1; //Assuming, -1 means NULL. } 
+3
source

If the value was NULL , then 0 will be returned by getInt , and then you can call wasNull to check if it was 0 or if it was NULL .

See also: wasNull ()

+2
source

you can use

 object obj = rs.getObject("CUST_TRAN_COUNT"); if (obj != null) { rs.getInt("CUST_TRAN_COUNT"); } 

but in some cases (very rarely) you cannot call getInt as soon as you called getObject, in which case you can simply use

 int.parse(obj.toString()) 

Also, I think the best way to do this,

  int value = rs.getInt("CUST_TRAN_COUNT"); boolean nullValue = rs.wasNull(); 

so if db returned null, the value will be 0, but nullValue will be true, so you can do the necessary

+1
source

There is wasNull in ResultSet or RowSet :

Reports whether the last read column was SQL NULL . Note that you must first call one of the getter methods in the column to try to read its value, and then call the wasNull method to find out if the read SQL value was NULL .

0
source

All Articles