how to add WHERE clause to Query on android

不打扰是莪最后的温柔 提交于 2020-01-01 08:20:49

问题


I would like to limit the results to those whose KEY_HOMEID is equal to journalId. I've been on this for a couple days any help would be appreciated.

public Cursor fetchAllNotes(String journalId) { return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_HEIGHT, KEY_BODY, KEY_HOMEID},"FROM DATABASE_TABLE WHERE KEY_HOMEID = journalId",null, null, null, null,null); }


回答1:


Have a look at http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query

Your query should look a little like this:

mDb.query(DATABASE_TABLE, // Table name
          columnNames, // String[] containing your column names
          KEY_HOMEID+" = "+jounalId, // your where statement, you do not include the WHERE or the FROM DATABASE_TABLE parts of the query,
          null,
          null,
          null,
          null
         );

If you feel more comfortable writing sql queries you can also use:

mDb.rawQuery("SQL STATEMENT", null);



回答2:


It makes your code more clear if you'll use it where arguments (in query parameters) Example:

        String [] settingsProjection = {
                DBContract.Settings._ID,
                DBContract.Settings.COLUMN_NAME_USER_ID,
                DBContract.Settings.COLUMN_NAME_AUTO_LOGIN
        };

        String whereClause = DBContract.Settings.COLUMN_NAME_USER_ID+"=?";
        String [] whereArgs = {userId.toString()};

        Cursor c = db.query(
                DBContract.Settings.TABLE_NAME,
                settingsProjection,
                whereClause,
                whereArgs,
                null,
                null,
                null
        );



回答3:


I was looking for an answer to my problem here as well.

It turned out that I tried to have a String instead of an Integer. My solution was to do it like that: 'String' instead of Integer.

Here is the code that worked for me in the end:

return db.query(TABLE_NAME_REMINDER, PROJECTION, REMINDER_REMINDER_TYPE+" = '"+rem_type+"'", null, null, null, null);


来源:https://stackoverflow.com/questions/3271740/how-to-add-where-clause-to-query-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!