Sqlite query returns 0, even if null

Below is the query that I use to get the int value corresponding to a specific field in my sqlite db table.

"SELECT conn_status FROM profiles WHERE devID = '" + id+"'"

If conn_status does not have a value that matches the provided devID, then the existing value in the table will be zero. I am retrieving data from java as shown:

c.getInt(c.getColumnIndex("conn_status"))

The problem here is that with this query, c.getInt returns 0, even if the value existing in the field is null. How can I change this query so that it returns a different value instead of 0, for example 5, if the value is null.

Any help is appreciated.

+5
source share
7 answers

isNull(). :

static int getInt(String columnName)
{
    if(c.isNull(c.getColumnIndex(columnName)))
        return -1;
    return c.getInt(c.getColumnIndex(columnName));
}
+15

SQLite IFNULL NULL:

SELECT IFNULL(conn_status, 5) FROM profiles WHERE devID = ?
+16

int Java null. , , getInt, 0. Integer , Integer int, 0

+3

, 5, , .

Cursor c = db.rawQuery("SELECT conn_status FROM profiles WHERE devID = '" + id+"'");

    if(c.getCount>0){
    int number = c.getInt(c.getColumnIndex(conn_status));
    return number;
    }else{
    return 5;
    }

cursor.getCount() -, , . , , databse . .

+2

Android Integer, , Integer NULL, primitive int . , .

/**
 * Return real integer of value or null
 * @param column_name Name of column in result
 */
public Integer getInt(String column_name){
    try{
        if(cursor.isNull(cursor.getColumnIndex(column_name)))
            return null;
        return cursor.getInt(cursor.getColumnIndex(column_name));
    }catch(Exception e){
        e.printStackTrace();
        Log.e("sqlite_exception", "column " + column_name + " not exists. " + e.getMessage());
        return null;
    }
}
0

, , getType().

Integer locationInfoId;

if (cursor.getType(columnIndex) == Cursor.FIELD_TYPE_NULL){
    locationInfoId = null;
} else {
    locationInfoId = cursor.getInt(columnIndex);
}

columnIndex++;
0

NULL , 0 c.getInt(index).

, NULL. 0 NULL 4 'n' 'u' 'l' 'l'. , NULL . , SQLite DB Browser.

, , .

I know this is an old question, but hopefully this will save someone else some troubleshooting time.

0
source

All Articles