# sqlalchemy.orm.exc.StaleDataError：对表 'users' 的 UPDATE 语句预期更新 1 行；但只匹配了 0 行。

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

## 根因

乐观并发控制：行被其他事务修改或删除。

## 版本兼容性

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

## 解决方案

1. **Refresh object before update.** (90% 成功率)
   ```
   session.refresh(user)
user.name = 'new_name'
session.commit()
   ```
2. **Use version counter in model.** (85% 成功率)
   ```
   class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    version_id = Column(Integer, nullable=False)
    __mapper_args__ = {'version_id_col': version_id}
   ```

## 无效尝试

- **Ignoring the error and retrying without refresh.** — Stale object leads to further inconsistencies. (80% 失败率)
- **Disabling versioning entirely.** — Loses concurrency protection; data corruption possible. (60% 失败率)
