What is the exact difference between using rawquery and execSQL ?? While writing a query in android activity, when to use rawquery and when to use execSQL ?
2 Answers
From API documentation:
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL (String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
The documentation is inconsistent but they behave both the same. Documentation of the latter is more in depth.
Cursor rawQuery (String sql, String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
Uses for rawQuery are:
- You want to query the database with a
SELECTstatement.
=>rawQuery("SELECT ...returns a set of rows and columns in aCursor.- It's more efficient to use
DatabaseUtils.longForQuery(SQLiteDatabase, String, String[])orDatabaseUtils.stringForQuery(...)in cases there is only a 1x1 query result, like fromSELECT count(*) FROM table(which also has it's own dedicated method:DatabaseUtils.queryNumEntries(...)) - this skips creation of aCursorobject & simplifies code since there is also nothing to close, moveToNext, etc.
- It's more efficient to use
- Special cases like
PRAGMA table_infothat returns data in rows (see this question) - Note: Do not use
rawQueryforINSERT,UPDATEorDELETEor anything else that modifies the database. You'll run into "Why does a delete rawQuery need a moveToFirst in order to actually delete the rows?". Reason being that queries can defer reading the result until needed (= access to the cursor) which means for SQLite delaying execution of the statement.
Uses for execSQL are:
- You have "instructions" for the database. Like
CREATE TABLE(or any otherCREATEstatement, e.g.CREATE INDEX),DROP,PRAGMAs that set properties rather than returning them, ... INSERT,UPDATEorDELETEwhen you're not interested in the amount of rows modified or the row id of the last insert.- When you need those, either use the
update(),insert(),delete()methods or use a second statement to read those:DatabaseUtils.longForQuerywith eitherSELECT last_insert_rowid()orSELECT changes(). Both return only 1 integer value. (see "Get updated rows count from SQLite in Android using a raw query?" and “SELECT last_insert_rowid()” returns always “0”)
- When you need those, either use the
- Anything else that relies on executing a statement.
1 Comment
Dileep Perla
got it clear .. execSQL doesnt return anything and used for creating,updating etc .. and rawQuery returns cursors etc.