# sqlalchemy.orm.exc.StaleDataError: 表 'users' 上的 UPDATE 语句预期匹配 1 行；实际找到 0 行

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

## 根因

乐观并发检查失败，因为自读取以来该行已被其他事务修改或删除。

## 版本兼容性

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

## 解决方案

1. **Re-query the object before updating** (95% 成功率)
   ```
   user = session.query(User).get(user_id)
if user:
    user.name = 'New Name'
    session.commit()
   ```
2. **Use session.refresh() to reload the object** (90% 成功率)
   ```
   session.refresh(user)
user.name = 'New Name'
session.commit()
   ```

## 无效尝试

- **Ignoring the error and retrying the update** — The row may have been deleted, so the update will still fail. (60% 失败率)
- **Disabling versioning in the model** — This removes concurrency protection, leading to potential data corruption. (80% 失败率)
