Android - sqlite in clause using string values from array?

穿精又带淫゛_ 提交于 2020-01-25 07:49:07

问题


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


回答1:


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



回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/29468610/android-sqlite-in-clause-using-string-values-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!