【问题标题】:Android studio: build sqlite select query dynamically depending on values in json arrayAndroid studio:根据 json 数组中的值动态构建 sqlite 选择查询
【发布时间】:2023-03-30 01:58:01
【问题描述】:

我在 Android 工作室 (java) 工作。 我正在使用一个 sqlite 数据库,我希望能够查询一个表。我目前将使用以下代码: ''

                    String strQuery = "select * from table where var1 = ?";

                    SQLiteStatement stmt = sqLiteDatabase.compileStatement(strQuery);
                    stmt.bindString(1, String.valueOf(strVarOne));
                    stmt.execute();

''

但我需要动态构建 WHERE 语句。我目前有一个 json 数组,我想用它来构建看起来像这样的 where 语句(例如)。

[{"country":"South Africa"},{"province":"Gauteng"}]

在上面的示例中,我希望查询如下所示:

"select * from table where country = 'South Africa' and province= 'Gauteng' "

任何人都可以帮助我如何根据 json 数组动态构建和运行该查询吗? 请记住,json 数组可能会发生变化 - 值可能不同,而且可能更多。

【问题讨论】:

  • 你的数据库表结构是什么?

标签: android sqlite android-studio where-clause


【解决方案1】:
class Place {
     @SerializedName("country")
     String country = null;
     @SerializedName("province")
     String province = null;
}

Type token = new TypeToken<ArrayList<Place>>(){}.type
String yourJson = "[{\"country":\"South Africa\"},{\"province\":\"Gauteng\"}]";
Gson gson = new Gson();

ArrayList<Place> places = gson.fromJson(yourJson, token);

String selectFormat = "select * from table where %$1s = '%$2s' and %$3s = '%$4s' "

ArrayList<String> selectArguments = new ArrayList<String>();

for(int i=0; i<places.size(); i++){
  if(places.country!=null){
     selectArguments.add("country");
     selectArguments.add(places.country);
  }else if(places.province != null) {
    selectArguments.add("province");
     selectArguments.add(places.province);
  }
}

我不会告诉你如何避免 SQL 注入。

String fullSQLStatement = String.format(selectFormat,selectArguments.toArray(new String[selectArguments.size()]);

fullSQLStatement 将变为 select * from table where country = 'South Africa' and province = 'Gauteng'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多