# sqlite3.IntegrityError: 外键约束失败

- **ID:** `python/sqlalchemy-sqlite-foreign-key-off`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

SQLite 默认不强制执行外键约束，除非设置 PRAGMA foreign_keys=ON；但如果关闭，引用完整性可能被违反，当打开时，现有错误数据会导致错误。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   Enable foreign key enforcement per connection: from sqlalchemy import event; @event.listens_for(engine, 'connect') def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor(); cursor.execute('PRAGMA foreign_keys=ON'); cursor.close()
   ```
2. **** (80% 成功率)
   ```
   Clean up orphaned records before enabling FK constraints.
   ```

## 无效尝试

- **** — Data inconsistency persists. (90% 失败率)
- **** — May lose data and doesn't fix the root cause. (60% 失败率)
