go data_error ai_generated true

sql:行已关闭,无法对结果调用 LastInsertId

sql: Rows are closed, cannot call LastInsertId on result

ID: go/sql-rows-err-lastinsertid

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
1证据数
2024-01-10首次发现

版本兼容性

版本状态引入弃用备注
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

根因分析

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

English

Calling Result.LastInsertId() on a sql.Result from an INSERT that used a SELECT or RETURNING clause, or after rows have been consumed.

generic

官方文档

https://pkg.go.dev/database/sql#Result.LastInsertId

解决方案

  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

无效尝试

常见但无效的做法:

  1. 90% 失败

    Rows.Close() closes the result set, making LastInsertId unavailable; order is wrong.

  2. 60% 失败

    db.Exec() returns a Result that supports LastInsertId, but if the INSERT has a RETURNING clause, it still fails.

  3. 95% 失败

    The result is tied to the original query; reconnecting doesn't recover the last insert ID.