0

In my search module I am using SQLite database. Sometimes I'm searching more than two values. So I am using AND condition and sometimes searching only one value. These two cases I need to implement in a single query. Please help me.

This is the query:

Cursor dbcur = myDB.rawQuery("select * from "+dbtable+" where Status='"+item+"'AND ball_court='"+ball+"'AND Tovendor='"+vendor+"'", null);

Sometimes I am searching status and ball_court, tovendor and sometimes I am searching status only. How to solve this problem?

Smi
  • 13,850
  • 9
  • 56
  • 64
user533787
  • 689
  • 2
  • 13
  • 28
  • Note you can format lines as code by indenting them four spaces. The "101\n010" button in the editor toolbar does this for you. Click the orange question mark in the editor toolbar for more information and tips on formatting. – outis Dec 11 '10 at 09:13

2 Answers2

0

Build the query string in stages, rather than all at once. If you're always going to select against the status, put that in the basic WHERE clause, then add any additional expressions. Use parameters (which you can do with SQLiteDatabase.query) rather than concatenating values into the query itself to prevent SQL injection. dbtable better not come from untrusted sources (e.g. users, the database itself). My Java's a little rusty, but try something like the following to start:

List<String> argList = new LinkedList<String>();

String selection = "Status=?";
argList.add(item);
if (ball != null && ball.length()) {
    selection += " AND ball_court=?";
    argList.add(ball);
}
if (vendor != null && vendor.length()) {
    selection += " AND Tovendor=?";
    argList.add(vendor);
}

String[] argArray = new String[argList.length()];
argList.toArray(argArray);
// columns is a String[] of column names
Cursor dbcur = myDB.query(false, dbtable, columns, selection, argArray, null, null, null);

Rather than appending strings, you might want to use a StringBuilder.

As for SELECT *, read "What is the reason not to use SELECT *?"

Community
  • 1
  • 1
outis
  • 75,655
  • 22
  • 151
  • 221
-1

You might be able to get some answers if you post a sample query as well as what you might search for! I didn't totally understand your question, as I would/should be able to help out.

Psycorpse
  • 11
  • 2
  • Cursor dbcur = myDB.rawQuery("select * from "+dbtable+" where Status='"+item+"'AND ball_court='"+ball+"'AND Tovendor='"+vendor+"'", null);..............This is my query.some time i am searching status and ball_court,tovendor and some i am searching status only.How to solve this problem.......Help me......... – user533787 Dec 11 '10 at 07:48
  • @user538689: You were probably downvoted since your answer doesn't actually answer the question. Normally, your post should have been a comment, but you need at least 50 rep to post comments on others' questions. To downvoter: user538689's "answer" should have been a comment, but user538689 can't post comments. – outis Dec 11 '10 at 09:58