How to use query for multiple selection argument u

2019-05-04 10:02发布

问题:

Here is my query :

// Table Name : Question

          Cursor cursor = db.query("QUESTION", new String[] { "TEXT", "OPTION_A",
            "OPTION_B", "OPTION_C", "OPTION_D", "OPTION_E",
            "RIGHT_ANSWER" },
            "SUBJECT=?", new String[] { "Ingles", "Historia" }, null,null,
            null);

I can have multiple subjects, right now i am having only two subjects(Ingles,Historia)

How to sort data by subjects using query??

I am getting bind or out of range error. I know error is somewhere in where clause , but not able to solve it.

回答1:

I got the answer.

1) To sort the data, need to enter column name in last argument

2) When multiple selection condition is available in one column use IN Operator.

 Cursor cursor = db.query("QUESTION", new String[] { "TEXT", "OPTION_A",
            "OPTION_B", "OPTION_C", "OPTION_D", "OPTION_E",
            "RIGHT_ANSWER" },
            "SUBJECT IN(?,?)", new String[] { "Ingles", "Historia" }, null,null,
            "SUBJECT");


回答2:

You are getting this error because number of "?" in where and array length in arguments mismatch. You can put condition like this
1) Using two conditions in where

Cursor cursor = db.query("QUESTION", new String[] { "TEXT", "OPTION_A", "OPTION_B", "OPTION_C", "OPTION_D", "OPTION_E", "RIGHT_ANSWER" }, "SUBJECT1=? AND SUBJECT2=? ", new String[] { "Ingles", "Historia" }, null,null, "SUBJECT");
2) Using IN condition
Cursor cursor = db.query("QUESTION", new String[] { "TEXT", "OPTION_A", "OPTION_B", "OPTION_C", "OPTION_D", "OPTION_E", "RIGHT_ANSWER" }, "SUBJECT IN(?)", new String[] { "Ingles,Historia" }, null,null, "SUBJECT");