Go:如何使用 NamedExec() 在 Postgresql 上获取最后一个插入 ID
Go: How to get last insert id on Postgresql with NamedExec()
我在我的 Go 应用程序中使用 jmoiron/sqlx 库与我的 PostgreSql 服务器通信。在我的应用程序的某个地方,我有以下代码:
sqlQuery := `
INSERT INTO table_to_insert (
code,
status,
create_time,
create_by
) VALUES (
'',
0,
CURRENT_TIMESTAMP,
0
) RETURNING id
`
datas, err := tx.NamedExec(sqlQuery, structToInsert)
问题:如何使用 tx.NamedExec()
中的 return 获取最后插入的 ID?我试过 datas.LastInsertId()
但总是 return 0.
注意:我确定插入到 postgres 是成功的。
resp.LastInsertID()
仅(通常)适用于 mySQL,并且仅适用于整数 ID:https://golang.org/pkg/database/sql/#Result
请注意,由于您正在使用 sqlx
(通过使用 NamedExec
),因此您需要使用 tx.Get
来执行查询并捕获 return 值:
// id should match the type of your ID
// e.g. int64 for a bigserial column, or string for a uuid
var id string
resp, err := tx.Get(&id, query, v1, v2, v3)
请参阅有关 sqlx GitHub 存储库的相关讨论:https://github.com/jmoiron/sqlx/issues/154#issuecomment-148216948
这是因为 PostgreSQL 没有 return 您最后插入的 ID。这是因为仅当您在使用序列的 table 中创建新行时,最后插入的 ID 才可用。
如果您实际在分配序列的 table 中插入一行,则必须使用 RETURNING
clause。像这样:INSERT INTO table (name) VALUES("val") RETURNING id"
。
我不确定您的驱动程序,但在 pq 中您将按以下方式执行此操作:
lastInsertId := 0
err = db.QueryRow("INSERT INTO brands (name) VALUES() RETURNING id", name).Scan(&lastInsertId)
我在我的 Go 应用程序中使用 jmoiron/sqlx 库与我的 PostgreSql 服务器通信。在我的应用程序的某个地方,我有以下代码:
sqlQuery := `
INSERT INTO table_to_insert (
code,
status,
create_time,
create_by
) VALUES (
'',
0,
CURRENT_TIMESTAMP,
0
) RETURNING id
`
datas, err := tx.NamedExec(sqlQuery, structToInsert)
问题:如何使用 tx.NamedExec()
中的 return 获取最后插入的 ID?我试过 datas.LastInsertId()
但总是 return 0.
注意:我确定插入到 postgres 是成功的。
resp.LastInsertID()
仅(通常)适用于 mySQL,并且仅适用于整数 ID:https://golang.org/pkg/database/sql/#Result
请注意,由于您正在使用 sqlx
(通过使用 NamedExec
),因此您需要使用 tx.Get
来执行查询并捕获 return 值:
// id should match the type of your ID
// e.g. int64 for a bigserial column, or string for a uuid
var id string
resp, err := tx.Get(&id, query, v1, v2, v3)
请参阅有关 sqlx GitHub 存储库的相关讨论:https://github.com/jmoiron/sqlx/issues/154#issuecomment-148216948
这是因为 PostgreSQL 没有 return 您最后插入的 ID。这是因为仅当您在使用序列的 table 中创建新行时,最后插入的 ID 才可用。
如果您实际在分配序列的 table 中插入一行,则必须使用 RETURNING
clause。像这样:INSERT INTO table (name) VALUES("val") RETURNING id"
。
我不确定您的驱动程序,但在 pq 中您将按以下方式执行此操作:
lastInsertId := 0
err = db.QueryRow("INSERT INTO brands (name) VALUES() RETURNING id", name).Scan(&lastInsertId)