开发者

What's the best way to form SQL queries in Android?

开发者 https://www.devze.com 2023-02-09 13:00 出处:网络
I have a database with five tables in an Android application. I have been surfing around looking for a way to put conditions in the query (WHERE, &&, OR).

I have a database with five tables in an Android application. I have been surfing around looking for a way to put conditions in the query (WHERE, &&, OR).

My queries are the form:

public Cursor getAlternative(int questionid) {
    Cursor cursor =  mDb.query(DBTABLE_ALTERNATIVE, new String[] { KEY_ALT }, KEY开发者_Go百科_QID + "=" + questionid, null, null, null, null, null);                
    return cursor;
}

But I find that many people write their queries with regular SQL, for ex:

Cursor c = myDB.query("SELECT FirstName,Age" +
                     " FROM " + MY_DATABASE_TABLE
                     + " WHERE Age > 10 LIMIT 7;",
                     null);

What is the most efficient way? To me it seems easier form regular SQL statements, but after reading the tutorials on the Android Dev site I started forming the queries like above.

Question 2: if I use the first way, how can I use two conditions? Say I have two parameters, questionid and categoryid, how do I put the next KEY_CID + "=" + categoryid in there?

I have tried with && and AND but none seem to work. Thanks.


What is the most efficient way?

It depends... but generally speaking the second way will be faster. Why? because it won't need to build the query string using the parameters that the query method takes.

However, I'd rather use the first way since it's less error prone.

Question 2. If I use the first way, how can I use two conditions?

It should work this way:

KEY_QID + "=" + questionid + " AND " +KEY_CATID + "=" + categoryid


I am not sure if the simple implications about String and StringBuffers (StringBuilder would even better) hold, as the SQL engine also needs to parse that query string again. The db.query() way may have the advantage that some parts of the query can be stored in a pre-parsed way (think "PreparedStatement"). Especially if the parameters are not put in the string, but as placeholders

E.g. where KEY_QID=? AND KEY_CATID=?

Here the basic query "stays constant" and the system can optimize.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号