1555 android data_error ai_generated true

android.database.sqlite.SQLiteConstraintException: 唯一约束失败:users.email (代码 1555)

android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: users.email (code 1555)

ID: android/sqliteconstraintexception-unique-constraint

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-04-20首次发现

版本兼容性

版本状态引入弃用备注
SQLite 3.42 active
Android 12 (API 31) active
Android 13 (API 33) active
Room 2.5.2 active

根因分析

INSERT 或 UPDATE 操作尝试在具有 UNIQUE 约束的列上设置一个表中已存在的值。

English

An INSERT or UPDATE operation attempted to set a value on a column with a UNIQUE constraint that already exists in the table.

generic

官方文档

https://developer.android.com/reference/android/database/sqlite/SQLiteConstraintException

解决方案

  1. Use INSERT OR REPLACE or INSERT OR IGNORE in your SQL statement. Example: ContentValues values = new ContentValues(); values.put("email", "[email protected]"); db.insertWithOnConflict("users", null, values, SQLiteDatabase.CONFLICT_REPLACE);
  2. Check for existing data before inserting: if (db.rawQuery("SELECT 1 FROM users WHERE email = ?", new String[]{email}).getCount() == 0) { db.insert(...); }
  3. Use Room's @Insert(onConflict = OnConflictStrategy.REPLACE) annotation to handle duplicate entries automatically.

无效尝试

常见但无效的做法:

  1. 95% 失败

    Clearing app cache does not affect the database, so the error persists.

  2. 75% 失败

    Adding a try-catch around the INSERT without handling the duplicate (e.g., ignoring the error) may cause data loss or silent failures.

  3. 85% 失败

    Disabling the unique constraint via ALTER TABLE may break data integrity and cause other bugs.