user4501847
user4501847

Reputation:

Android - sqlite in clause using string values from array?

I want to execute a sqlite query, I have a String :

 String A = "AB-CDFER-GTDOL";
 String[] parts = Pattern.compile("-", Pattern.LITERAL).split(A);

Now I need to use from parts in my query.

cursor = sql.rawQuery("SELECT * FROM MyTable WHERE Comment in" + ?????, null);

How I can use from parts in my query.

For example I need to have ("AB","CDFER","GTDOL")

Upvotes: 0

Views: 817

Answers (3)

Stan
Stan

Reputation: 6561

You can compile a string after split:

         String A = "AB-CDFER-GTDOL";
         String[] parts = Pattern.compile("-", Pattern.LITERAL).split(A);
    // build the params string
    StringBuilder sb = new StringBuilder("");
    for(String param:parts){
    // you can also enclose it in quotes
    sb.append",".append('"').append(param).append('"');
    }
    // remove 1st comma from sb.
    final String params = sb.toString().substr(1);

The trick here is to compile needed string as "AB","CDFER","GTDOL". Now you can pass this string as a ONE paramenter.

cursor = sql.rawQuery("SELECT * FROM MyTable WHERE Comment in(?)", new String[]{params});

Upvotes: 1

rubengees
rubengees

Reputation: 1850

You can use the query Method from Android SQLDatabase. This is the Documentation for it: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query

You could implement it like the following:

 String A = "AB-CDFER-GTDOL";
 String[] parts = A.split("-");
 cursor = sql.query("MyTable", null, "Comment = ?", parts, null, null, null, null);

A helpful Article about SQL in Android: http://hmkcode.com/android-simple-sqlite-database-tutorial/

Upvotes: 0

keshav kowshik
keshav kowshik

Reputation: 2374

I hope this will solve your problem:

You can split your string in the following way:

String A = "AB-CDFER-GTDOL";
 String[] parts = A.split("-");

Now your parts array will have the following values:

parts[0] = "AB";
parts[1] = "CDFER" etc..

Similarly you can use these value in your sql query as needed.

Hope this helps.

Upvotes: 0

Related Questions