【问题标题】:Insert only if entry doesn't exit仅在条目不退出时插入
【发布时间】:2014-10-15 17:52:21
【问题描述】:

在我的 Android 应用程序中,我下载了一个 JSON 文件,我对其进行解析并将 JSONObject 的每个条目写入本地 SQLite 数据库。这是我的代码:

public void myMethod() {
        JSONArray myJA = connectAndCreateJsonArray(url);
        localDB.beginTransaction();

        for (int i = 0; i < lenght; i++) {
            JSONObject jObj = (JSONObject) myJA.getJSONObject(i);
            localDB.insert("users", null, getParsedMerchantEntry(jObj));
        }

        localDB.setTransactionSuccessful();
}

这是 connectAndCreateJsonArray() 的主体:

    private JSONArray connectAndCreateJsonArray(String url) {
        JSONArray jsonArray = new JSONArray();

        try {   
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            request.addHeader("Cache-Control", "no-cache");
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            InputStreamReader in = new InputStreamReader(entity.getContent());
            BufferedReader reader = new BufferedReader(in);
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line=reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            jsonArray = new JSONArray(stringBuilder.toString());

        } catch (IllegalStateException e) {
            e.printStackTrace();                
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonArray;
    }

这里是 getParsedMerchantEntry() 的主体:

    private ContentValues getParsedMerchantEntry(JSONObject entry) {
        ContentValues values = new ContentValues();

        values.put("id", entry.optString("id").toString());
        values.put("city", entry.optString("city").toString());
        values.put("name", entry.optString("firstname").toString());
        values.put("surname", entry.optString("lastname").toString());

        return values;
    }

如果本地数据库中已经存在该条目,有什么方法可以避免调用 localDB.insert()?

【问题讨论】:

  • 在插入之前对id 进行查询不会增加太多开销
  • 您也可以尝试插入和捕获,但如果 ID 已存在则忽略失败。这样你就不会只是为了转身而读书。

标签: android json database sqlite insert


【解决方案1】:

您必须使用查询来处理此问题

这是示例方式。

ContentValues insertValues = new ContentValues();
insertValues.put("id", qclass);
insertValues.put("question", question);

yourDbName.insertWithOnConflict(DATABASE_TABLE, null, insertValues, SQLiteDatabase.CONFLICT_IGNORE); 

确保您的 Id 字段创建为非空且唯一。

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    相关资源
    最近更新 更多