使用参数null查询SQLite

时间:2014-09-15 03:09:20

标签: android sql android-sqlite

我在query()语句中使用String selectionArgs。我想要一个包含2个参数的查询。但它们可以为null,我需要使用两个查询。

String where="";
String []params=null;
if(hasAge){
   where="UID = ? AND Age > ?";
   params=new String[] { String.valueOf(iud), String.valueOf(age) };
}else{
   where="UID = ? ";
   params=new String[] { String.valueOf(iud) };
}
Cursor cur = sqlite_obj.query(TableName, null, where, params, null, null, null, null);

如果我有5个参数。我怎么查询?

1 个答案:

答案 0 :(得分:1)

在数组中构建参数并将它们连接到带有'的字符串。和'。

伪代码

columns = {col1, col2, col3, col4, col5}; // string array
cols = {}; // string array
vals = {}; // string array

for(i=0,j=0; i<columns.length; i++){
    if(canuse(columns[i])){
        cols[j] = columns[i] + " = ? ";
        vals[j] = value(columns[i]);
        j++;
    }
}

sqlite_obj.query(TableName, null, cols.joinwith(" AND "), vals, null, null, null, null);