# sql：行已关闭，无法对结果调用 LastInsertId

- **ID:** `go/sql-rows-err-lastinsertid`
- **领域:** go
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

对来自使用 SELECT 或 RETURNING 子句的 INSERT 的 sql.Result 调用 Result.LastInsertId()，或在行已被消耗后调用。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Go 1.15 | active | — | — |
| Go 1.16 | active | — | — |
| Go 1.17 | active | — | — |
| Go 1.18 | active | — | — |
| Go 1.19 | active | — | — |
| Go 1.20 | active | — | — |
| Go 1.21 | active | — | — |
| Go 1.22 | active | — | — |
| Go 1.23 | active | — | — |

## 解决方案

1. ```
   Use db.Exec() for INSERT statements without RETURNING; use db.QueryRow() with RETURNING and scan into a variable
   ```
2. ```
   Access LastInsertId immediately after Exec() before any rows iteration
   ```
3. ```
   For PostgreSQL with RETURNING, use a separate SELECT currval() or lastval() query
   ```

## 无效尝试

- **** — Rows.Close() closes the result set, making LastInsertId unavailable; order is wrong. (90% 失败率)
- **** — db.Exec() returns a Result that supports LastInsertId, but if the INSERT has a RETURNING clause, it still fails. (60% 失败率)
- **** — The result is tied to the original query; reconnecting doesn't recover the last insert ID. (95% 失败率)
