You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用中SQLite的insertWithOnConflict方法失效问题求助

Fixing insertWithOnConflict(CONFLICT_IGNORE) Not Working in SQLite for Android

Hey there! Let's break down why your duplicate-ignore insert isn't working and how to fix it.

The Root Cause

SQLite's conflict handling (like CONFLICT_IGNORE) only kicks in when there's a primary key or unique constraint violation. Right now, your table doesn't have a unique constraint on the field you're using to define "duplicates" (looks like pattern_name), so the database has no way to detect duplicates—hence it just inserts every row regardless.

Step 1: Add a Unique Constraint to Your Table

First, make sure your table is created with a UNIQUE constraint on the pattern_name column. If you're creating the table for the first time, use a statement like this:

CREATE TABLE " + TABLE_NAME + " (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pattern_name TEXT UNIQUE, -- This enforces uniqueness for duplicate checks
    value TEXT
);

If your table already exists and has data:

  1. First back up any existing data to avoid loss
  2. Use this ALTER TABLE statement to add the unique constraint (note: this will fail if there are already duplicate pattern_name entries—clean those up first):
    ALTER TABLE " + TABLE_NAME + " ADD CONSTRAINT unique_pattern_name UNIQUE (pattern_name);
    

Step 2: Clean Up Your Insert Code

Looking at your code, the second parameter in insertWithOnConflict ("pattern_name") is only used when you're inserting an empty ContentValues (to set a NULL value for that column). Since you're passing valid values, you can safely set this to null:

public void AddPattern(Pattern_Model pattern_model) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("pattern_name", pattern_model.getPattern_name());
    values.put("value", pattern_model.getPattern_value());
    
    // Use null for the second parameter (it's irrelevant here)
    long ln = db.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    
    db.close();
    if(ln != -1){
        Log.d("replace", "ok");
    }
}

How to Verify

After adding the unique constraint, when you try to insert a row with a pattern_name that already exists:

  • The ln return value will be -1
  • The duplicate row won't be inserted (exactly what you want!)

内容的提问来源于stack exchange,提问作者Priyanka Prajapati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:25:45