# SQLAlchemy完整性错误：（sqlite3.完整性错误）唯一约束失败：users.email

- **ID:** `python/flask-sqlalchemy-commit-error`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

尝试向具有唯一约束的列插入重复值。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Check for existing record before insertion** (95% 成功率)
   ```
   existing = User.query.filter_by(email=email).first()
if not existing:
    db.session.add(new_user)
    db.session.commit()
   ```
2. **Use save-or-update logic** (90% 成功率)
   ```
   user = User.query.filter_by(email=email).first()
if user:
    user.name = name
else:
    user = User(email=email, name=name)
db.session.add(user)
db.session.commit()
   ```

## 无效尝试

- **Ignoring the error and retrying the commit** — Same error will occur if duplicate data is not resolved. (95% 失败率)
- **Removing the UNIQUE constraint from the database** — Compromises data integrity; allows duplicate emails. (60% 失败率)
