使用Postgres:对于非顺序标识符的LastInsertedId

huangapple go评论74阅读模式
英文:

Go with Postgres: LastInsertedId for non sequential identifiers

问题

我正在使用Go编写一个小型Web服务,通过pq驱动程序包使用Postgres。

我正在使用uuid作为我的模型标识符,所以LastInsertId无法使用。

所以我在考虑可以这样做:

var id string
res, err := session.Exec("INSERT INTO todos (text, list_id) VALUES ($1, $2) RETURNING todo_id", text, listId).Scan(&id)

Scan似乎与Exec不太兼容。

那么,我如何从我的新todo行中返回uuid呢?

英文:

I´m writing a small web service in Go which uses Postgres through the pq driver package.

I´m using a uuid´s as identifier for my models so LastInsertId won´t work.

So I´m thinking I could something like this:

  var id string
  res, err := session.Exec("INSERT INTO todos (text, list_id) VALUES ($1, $2) RETURNING todo_id", text, listId).Scan(&id)

Scan does seem to play well with Exec.

So how do I return the uuid from my new todo row?

答案1

得分: 3

根据https://godoc.org/github.com/lib/pq#hdr-Queries上的内容,看起来你应该使用QueryRow而不是Exec。

pq不支持数据库/sql中Result类型的LastInsertId()方法。要返回INSERT(或UPDATE或DELETE)的标识符,请使用带有标准Query或QueryRow调用的Postgres RETURNING子句:

var userid int
err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
    VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)
英文:

From https://godoc.org/github.com/lib/pq#hdr-Queries it looks like you should use QueryRow instead of 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)

huangapple
  • 本文由 发表于 2016年10月5日 01:05:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/39858020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定