Wen*_*Adi 19 postgresql go sqlx
我使用jmoiron/sqlx库与我的Go应用程序中的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)
Run Code Online (Sandbox Code Playgroud)
问题:如何使用返回来获取最后一个插入ID tx.NamedExec()?我已经尝试datas.LastInsertId()但它总是返回0.
注意:我确定插入postgres是成功的.
Sal*_*ali 25
这是因为PostgreSQL没有返回最后插入的id.这是因为只有在使用序列的表中创建新行时,最后插入的ID才可用.
如果您实际在分配序列的表中插入一行,则必须使用RETURNING子句.像这样:INSERT INTO table (name) VALUES("val") RETURNING id".
我不确定你的驱动程序,但是在pq中你将通过以下方式执行此操作:
lastInsertId := 0
err = db.QueryRow("INSERT INTO brands (name) VALUES($1) RETURNING id", name).Scan(&lastInsertId)
Run Code Online (Sandbox Code Playgroud)
resp.LastInsertID()仅(通常)与mySQL一起使用,仅适用于整数ID:https://golang.org/pkg/database/sql/#Result
请注意,由于您正在使用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)
Run Code Online (Sandbox Code Playgroud)
请参阅有关sqlx GitHub存储库的相关讨论:https://github.com/jmoiron/sqlx/issues/154#issuecomment-148216948