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

- **ID:** `android/sqliteconstraintexception-unique-constraint`
- **领域:** android
- **类别:** data_error
- **错误码:** `1555`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

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

## 解决方案

1. ```
   Use INSERT OR REPLACE or INSERT OR IGNORE in your SQL statement. Example: ContentValues values = new ContentValues(); values.put("email", "test@example.com"); 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.
   ```

## 无效尝试

- **** — Clearing app cache does not affect the database, so the error persists. (95% 失败率)
- **** — Adding a try-catch around the INSERT without handling the duplicate (e.g., ignoring the error) may cause data loss or silent failures. (75% 失败率)
- **** — Disabling the unique constraint via ALTER TABLE may break data integrity and cause other bugs. (85% 失败率)
