Go:如何在带有NamedExec()的Postgresql上获取最后一个插入id
我在Go应用程序中使用库与PostgreSql server通信。在我的应用程序中,我有以下代码:Go:如何在带有NamedExec()的Postgresql上获取最后一个插入id,postgresql,go,sqlx,Postgresql,Go,Sqlx,我在Go应用程序中使用库与PostgreSql server通信。在我的应用程序中,我有以下代码: sqlQuery := ` INSERT INTO table_to_insert ( code, status, create_time, create_by ) VALUES ( '', 0, CURRENT_TIMESTAMP, 0 ) R
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()
返回的值获取最后一个插入id?我尝试了datas.LastInsertId()
,但它总是返回0
注意:我确信插入postgres成功。resp.LastInsertID()仅(通常)适用于mySQL,并且仅适用于整数ID:
请注意,由于您使用的是sqlx
(通过使用NamedExec
),因此您需要使用tx.Get
执行查询并捕获返回值:
// 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 repo上的相关讨论:原因是PostgreSQL不会返回最后插入的id。这是因为只有在使用序列的表中创建新行时,最后插入的id才可用 如果您实际在分配序列的表中插入一行,则必须使用。类似这样的内容:
插入表(名称)值(“val”)返回id“
我不确定你的司机是谁,但在这方面,你将采用以下方式:
lastInsertId := 0
err = db.QueryRow("INSERT INTO brands (name) VALUES($1) RETURNING id", name).Scan(&lastInsertId)