30.04.2013 Views

Android - CommonsWare

Android - CommonsWare

Android - CommonsWare

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Managing and Accessing Local Databases<br />

If your queries are pretty much "baked into" your application, this is a very<br />

straightforward way to use them. However, it gets complicated if parts of<br />

the query are dynamic, beyond what positional parameters can really<br />

handle. For example, if the set of columns you need to retrieve is not<br />

known at compile time, puttering around concatenating column names<br />

into a comma-delimited list can be annoying...which is where query()<br />

comes in.<br />

Regular Queries<br />

The query() method takes the discrete pieces of a SELECT statement and<br />

builds the query from them. The pieces, in order that they appear as<br />

parameters to query(), are:<br />

• The name of the table to query against<br />

• The list of columns to retrieve<br />

• The WHERE clause, optionally including positional parameters<br />

• The list of values to substitute in for those positional parameters<br />

• The GROUP BY clause, if any<br />

• The ORDER BY clause, if any<br />

• The HAVING clause, if any<br />

These can be null when they are not needed (except the table name, of<br />

course):<br />

String[] columns={"ID", "inventory"};<br />

String[] parms={"snicklefritz"};<br />

Cursor result=db.query("widgets", columns, "name=?",<br />

parms, null, null, null);<br />

Building with Builders<br />

Yet another option is to use SQLiteQueryBuilder, which offers much richer<br />

query-building options, particularly for nasty queries involving things like<br />

the union of multiple sub-query results. More importantly, the<br />

306<br />

Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!