Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check an int variable is null or is empty from the Database [duplicate]

Tags:

java

jdbc

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");
        }

%>
like image 406
maas Avatar asked Sep 14 '11 06:09

maas


People also ask

Is NULL or empty for int?

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).

Is NULL or empty in SQL query?

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).

Can an int variable be NULL?

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.


2 Answers

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.

like image 105
Joachim Sauer Avatar answered Oct 09 '22 16:10

Joachim Sauer


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.
}
like image 41
Buhake Sindi Avatar answered Oct 09 '22 18:10

Buhake Sindi