Android Tutorial

(avery) #1
Android Tutorial 315

returns a Cursor of results. If you know your SQL and you don’t
want to bother learning the ins and outs of all the different SQL
query building utilities, this is the method for you.

For example, let’s say we have a UNION query. These types of
queries are feasible with the QueryBuilder, but their
implementation is cumbersome when you start using column
aliases and the like.

Let’s say we want to execute the following SQL UNION query,
which returns a list of all book titles and authors whose name
contains the substring ow (that is Hallows, Rowling), as in the
following:

SELECT title AS Name,
„tbl_books‟ AS OriginalTable
FROM tbl_books
WHERE Name LIKE „%ow%‟
UNION
SELECT (firstname||‟ „|| lastname) AS Name,
„tbl_authors‟ AS OriginalTable
FROM tbl_authors
WHERE Name LIKE „%ow%‟
ORDER BY Name ASC;


We can easily execute this by making a string that looks much like
the original query and executing the rawQuery() method.

String sqlUnionExample = “SELECT title AS Name, „tbl_books‟ AS
OriginalTable from tbl_books WHERE Name LIKE? UNION SELECT
(firstname||‟ „|| lastname) AS Name, „tbl_authors‟ AS OriginalTable
from tbl_authors WHERE Name LIKE? ORDER BY Name ASC;”;
Cursor c = mDatabase.rawQuery(sqlUnionExample,
new String[]{ “%ow%”, “%ow%”});

Free download pdf