Performing Database Related Operations on Android using SQLite

2 min read
Performing Database Related Operations on Android using SQLite

Hello folks. I have had issues with Android Databases in the past. Many a time I could not get it working due to problems. As I slowly started searching through docs on the web, I could gain knowledge on SQLite. In today’s blog post, I will be decribing how to do basic DB Related Operations on Android using SQLite


Suppose you wanted to write a query like

SELECT * FROM Question , Category WHERE enabled=1 AND Category.CAT = Question.CAT

Of course, you could write this whole expression inside a String and then use the db.execSQL() method. You would have to waste the space required for a String and the Cursor. Using the query() method, you will need to waste the space only for the Cursor. Here is the syntax for the query() method:

public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

Here are what each of them mean:
table : The table name to compile the query against
columns : A list of columns that have to be returned in the query. Passing null returns all columns (Synchronous to SELECT * FROM ...), which is discouraged
selection : This declares which rows to return. This would be synchronous to the SQL WHERE command (eg. SELECT * FROM Category WHERE enabled=1)
selectionArgs : You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values which are returned will be bound as Strings.
groupBy : Filter declaring how the rows must be grouped, synchronous to SQL GROUP BY command. Passing null would result in no grouping of the output
having : A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause. Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy : This states how to order the rows, synchronous to SQL ORDER BY command. Passing null, will return the output as is without any ordering
limit : Limits the number of rows returned

This function returns a Cursor object which is placed before the first row.

(To be continued..)


🎉 You've successfully subscribed to Sparker0i's Blog!