2

在我的项目中,我必须选择多个值并将其传递给查询。即 page1 包含复选框。我将选定的复选框 id 存储到一个数组中。我正在改组该数组并随机获取值。现在我需要将这些随机值传递给查询。在数据库中使用 IN 运算符我可以静态传递值,但是如何将值动态传递给查询。

例如:(静态传递值)

SELECT * FROM Persons WHERE person_id IN ('21','22')

在上面的查询中,id 的 21 和 22 是先前已知的,因此我们静态传递,但我想发送值以动态查询。

Page1:
public static ArrayList<String> chksublist = new ArrayList<String>();

Page2:
 Collections.shuffle(chksublist );
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above line I want to send the random values which are in chksublist array.
4

4 回答 4

2

String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ")";

但是在将其发送到 SQL 查询之前对其进行改组对chksublist您从 SQL 获得的结果集没有影响。它不会随机排列您的结果。删除Collections.shuffle(chksublist);并使用

String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ") ORDER BY RANDOM()";

于 2012-09-03T06:34:55.183 回答
1

看看值是如何动态传递的

  // Getting single contact
 public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
        KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
        new String[] { String.valueOf(id) }, null, null, null, null);

 // here   new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function
if (cursor != null)
    cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1), cursor.getString(2));
// return contact
return contact;
 }
于 2012-09-03T06:22:46.040 回答
1

您可以像这样生成查询

int values[];      //it contains your generated values like 21,22....
String query="SELECT * FROM Persons WHERE person_id IN (";

for(int i=0;i<values.length;i++){
query=query+"'"+values[i]+"'";
if(i<values.length-1){
query=query+",";    //No , after last values
} 

}
query+=")";

最后通过这个查询。

于 2012-09-03T06:29:02.697 回答
0

尝试一下

cursor = database.query(tablename,
                    new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null);

使用原始查询

String query = "SELECT * FROM Persons WHERE person_id IN ("+parameter1+","+parameter2+")";
db.rawQuery(query);
于 2012-09-03T06:30:49.813 回答