开发者

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 SQLiteDatab开发者_如何学编程ase/Cursor object.


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.


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


If you're retrieving a primary key then you can use the statement getGeneratedKeys method which returns a resultSet of generated keys after an insert.


Giving the database object is db

long result = db.compileStatement("select count(*) from some_table").simpleQueryForLong();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜