Thanos
Thanos

Reputation: 41

Query SQLite with parameters null

I use the String selectionArgs in query() statement. I want a query with 2 parameters. But they can null, and I need to use two querys.

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);

If I have 5 parameters. How I query ?

Upvotes: 0

Views: 538

Answers (1)

kums
kums

Reputation: 2691

Build the parameters in an Array and join them to a string with ' AND '.

Pseudo Code

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);

Upvotes: 1

Related Questions