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();
精彩评论