Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How can I port ExecuteScalar to Java?

SqlCommand.ExecuteScalar Method
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

I guess this will involve heavy use of generics.

Assume I have an SQLiteDatabase/Cursor object.

like image 388
Caner Avatar asked Mar 03 '26 10:03

Caner


2 Answers

Have a look at SQLLiteStatement

long simpleQueryForLong() Execute a statement that returns a 1 by 1 table with a numeric value.

String simpleQueryForString() Execute a statement that returns a 1 by 1 table with a text value.

like image 54
blank Avatar answered Mar 05 '26 22:03

blank


This logic worked for me:

public int ExecuteScalar(/* code...*/) {
    Cursor cursor = database.rawQuery(sql, selectionArgs);
    try {
        cursor.moveToNext();
        int val = cursor.getInt(0);
        cursor.close();
        return val;
    }   
    catch (Exception e) {
        /* code...*/
    }
    return -1;
}
like image 24
Caner Avatar answered Mar 05 '26 23:03

Caner