# sqlalchemy.exc.StaleDataError: 对 'users' 表的 UPDATE 语句预期更新 1 行，但实际匹配到 0 行。

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

## 根因

在 SELECT 和 UPDATE 之间，另一个事务删除或修改了该行，导致 ORM 的版本检查或行计数失败。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   Implement optimistic locking with version_id_col: class User(Base): __mapper_args__ = {'version_id_col': version}
   ```
2. **** (85% 成功率)
   ```
   Catch StaleDataError and retry the whole transaction with fresh data: for attempt in range(3): try: update() break except StaleDataError: session.rollback()
   ```

## 无效尝试

- **** — Autoflush doesn't affect the underlying row version; the issue is concurrent modification, not flush timing. (70% 失败率)
- **** — Refresh may still see stale data if the other transaction hasn't committed yet; it doesn't solve the race condition. (60% 失败率)
