Android: How can I port ExecuteScalar to Java?

倾然丶 夕夏残阳落幕 提交于 2019-12-01 20:17:55

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!