Android – SQLiteQueryBuilder.query() vs SQLiteDatabase.query()

androidsqlite

What's the difference between these two approaches?
For me it seems that the only benefit of SQLiteDatabase is its ability to work with different databases. Am I right?

Best Answer

The primary method is SQLiteDatabase#rawQuery(). Both SQLiteDatabase#query() and SQLiteQueryBuilder are just helpers to compose the SQL.

The SQLiteDatabase#query() can only compose simple queries from one table. The SQLiteQueryBuilder can create joins, unions and such. Since SQLiteQueryBuilder is an extra object, you'd only construct it if you need it's power.

Personally I think that any non-trivial SQL is easier to read as SQL than as pieces composed with helper like this, so I'd use rawQuery over SQLiteQueryBuilder, but that's a matter of taste and how well you know SQL. The SQLiteQueryBuilder might also be useful if you have some common subqueries that you want to compose together in different ways.

In fact I would prefer to use prepared statements, because compilation of SQL is slow compared to it's execution, and because it avoids doing string operations on potentially untrusted values. I couldn't find the API at first, because for some strange reason it is called SQLiteDatabase#compileStatement rather than the usual prepare used in the underlying C API.