0

you get data out of the columns using pre-provided methods such as getInt(...), getString(...), but how do you get data out of something like a SELECT statement, in sqlite the statement I'd like to do something like:

SELECT COUNT(COLUMN_NAME) FROM TABLE_NAME

how would you execute this query and then get the result to an int variable?

2 Answers 2

1

You do it the same way:

String sql = "SELECT COUNT(COLUMN_NAME) FROM TABLE_NAME";

So if you create a Cursor object with rawQuery():

Cursor c = db.rawQuery(sql, null);

this Cursor contains only 1 column and you can get its value with:

if (c.moveToFirst()) result = c.getInt(0);

where result is a predefined int variable.
But it's a good practice to alias the returned column, like:

String sql = "SELECT COUNT(COLUMN_NAME) AS counter FROM TABLE_NAME";

so you can get it by its name:

if (c.moveToFirst()) result = c.getInt(c.getColumnIndex("counter"));
Sign up to request clarification or add additional context in comments.

6 Comments

I didnt ask it in the main question, but do you know if android provides a way to select the nth row in a table, or should we use something like the limit clause and select the last row?
You must use limit but with an ORDER BY clause, like: select * from tablename order by id limit 10
but use the order by? the LIMIT clause disorganizes rows?(I'm not very familiar with sql itself)
Tables are unordered datasets. What you think as first 10 rows might not be what you will get with: select * from tablename limit 10. You can do it but there is no guarantee for the result.
This applies to any rdbms that I know of.
|
1

Create a Dao CLASS which include count method which returns count of the TABLE_NAME

@Dao
abstract class TABLE_NAMEDao : BaseDao<TABLE_NAME> {
@Query("SELECT COUNT(id) FROM TABLE_NAME")
    abstract fun count(): Long
}

1 Comment

I don't quite understand kotlin, would it be possible to also provide the java version alongside?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.