# sqlalchemy.exc.IntegrityError：(sqlite3.IntegrityError) UNIQUE 约束失败：user.email

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

## 根因

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

## 版本兼容性

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

## 解决方案

1. **** (85% 成功率)
   ```
   if not User.query.filter_by(email=email).first():
    db.session.add(user)
    db.session.commit()
   ```
2. **** (90% 成功率)
   ```
   from sqlalchemy.dialects.postgresql import insert
stmt = insert(User).values(email=email).on_conflict_do_nothing()
   ```

## 无效尝试

- **** — Silently fails to create the user, leading to inconsistent state. (70% 失败率)
- **** — Allows duplicate emails, breaking application logic. (90% 失败率)
