使用 Postgres:用于非顺序标识符的 LastInsertedId
Go with Postgres: LastInsertedId for non sequential identifiers
我正在用 Go 编写一个小型 Web 服务,它通过 pq driver package 使用 Postgres。
我使用 uuid 作为我的模型的标识符,因此 LastInsertId 不起作用。
所以我想我可以这样做:
var id string
res, err := session.Exec("INSERT INTO todos (text, list_id) VALUES (, ) RETURNING todo_id", text, listId).Scan(&id)
Scan
似乎与 Exec
配合得很好。
那么我如何 return 我的新待办事项行中的 uuid?
从 https://godoc.org/github.com/lib/pq#hdr-Queries 看来您应该使用 QueryRow 而不是 Exec
pq does not support the LastInsertId() method of the Result type in database/sql. To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres RETURNING clause with a standard Query or QueryRow call:
var userid int
err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)
我正在用 Go 编写一个小型 Web 服务,它通过 pq driver package 使用 Postgres。
我使用 uuid 作为我的模型的标识符,因此 LastInsertId 不起作用。
所以我想我可以这样做:
var id string
res, err := session.Exec("INSERT INTO todos (text, list_id) VALUES (, ) RETURNING todo_id", text, listId).Scan(&id)
Scan
似乎与 Exec
配合得很好。
那么我如何 return 我的新待办事项行中的 uuid?
从 https://godoc.org/github.com/lib/pq#hdr-Queries 看来您应该使用 QueryRow 而不是 Exec
pq does not support the LastInsertId() method of the Result type in database/sql. To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres RETURNING clause with a standard Query or QueryRow call:
var userid int
err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)