I am working on a project and now I have been stuck on a weird stage.
I know that we can execute any query that has to do anything with database we can write that using:
Cursor cursor = db.rawQuery("SELECT * FROM table_name", null);
But now I want to execute this query:
"SELECT strftime('%s','now','-2 day')"
Generally the above query returns unixepoch time of one day before yesterday.
Does anyone know how can I get this done?
You would handle this query like any other query:
Cursor cursor = db.rawQuery("SELECT strftime('%s','now','-2 day')", null);
try {
if (cursor.moveToFirst()) {
long seconds = cursor.getLong(0);
...
} else {
// cannot happen with this query
}
} finally {
cursor.close();
}
If you want to access the column by name (which is completely pointless if you have only a single column), you can give it an alias:
cursor = db.rawQuery("SELECT strftime(...) AS s", null);
cursor.getColumnIndexOrThrow("s"); // returns zero
...
Please note that for queries that return a single value, there is a helper function:
long seconds = DatabaseUtils.longForQuery(
db, "SELECT strftime('%s','now','-2 day')", null);