Android: How can I port ExecuteScalar to Java?

醉酒当歌 提交于 2019-12-01 22:10:12

问题


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.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


Giving the database object is db

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


来源:https://stackoverflow.com/questions/7348644/android-how-can-i-port-executescalar-to-java

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