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");
}
%>
Int is a value type so it cannot be null. Empty value of int depends on the logic of your application - it can be 0 or -1 or int. MinValue (well, technically, any number).
A null database field means that there is no value for a given record. It indicates the absence of a value. A blank database field means that there is a value for a given record, and this value is empty (for a string value) or 0 (for a numeric value).
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
int
can't be null
, because it's a primitive type.
For the same reason ResultSet.getInt()
can't return null
.
You will need to call ResultSet.wasNull()
right after your getInt()
call to check if the value was null
.
Note that since int
can't be null
, nocustomer
will have a value even if the database value is null
. getInt()
is defined to return 0
when the DB value is null
, so nocustomers
will be 0
.
At compile time, the java compiler will complain with the following message:
incomparable types: int and <nulltype>
if (nocustomers == null) {
^
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):
nocustomers = rs.getInt("CUST_TRAN_COUNT");
if (rs.wasNull()) {
nocustomers = -1; //Assuming, -1 means NULL.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With