使用Go的sqlx包和Postgres运行UPDATE查询时,你能否检索到更新行的列表?

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

Can you retrieve a list of updated rows when running an UPDATE query using the Go sqlx package with Postgres?

问题

我正在使用Go的sqlx包(标准database/sql包的扩展)与Postgres数据库运行一个查询。它的代码大致如下:

result, err := s.getDB(tx).Exec(`
	UPDATE table_name
	SET var_name = 0
	WHERE var_name = 1;`)
if err != nil {
	return nil, err
}

在不使用托管事务的情况下,如何获取已更新行的列表?或者至少获取已更新行的主键列表?

英文:

I have a query I'm running using Go's sqlx package (an extension to the standard database/sql package) with a Postgres database. It looks something like this:

result, err := s.getDB(tx).Exec(`
	UPDATE table_name
	SET var_name = 0
	WHERE var_name = 1;`)
if err != nil {
	return nil, err
}

Without using a managed transaction, how can I retrieve the list of updated rows? Or at least a list of primary keys for the updated rows?

答案1

得分: 3

使用PostgreSQL的RETURNING子句和db.Query/db.Select变体来替代Exec,例如:

//获取更新行的主键
db := s.getDB(tx)

results := []int{}
err = db.Select(&results, "UPDATE mytable SET var_name = 0 WHERE var_name = 1 RETURNING id")

要检索多个列,只需在RETURNING后面列出列名,例如:

rows, err := db.Queryx("UPDATE mytable SET var_name = 0 WHERE var_name = 1 RETURNING id,var_name,other_columns")
for rows.Next() {
    //对结果进行处理
}
英文:

Use PostgreSQL's RETURNING clause and db.Query/db.Select variants instead of Exec, e.g.

//get the primary key of updated rows
db := s.getDB(tx)

results := []int{}
err = db.Select(&results, "UPDATE mytable SET var_name = 0 WHERE var_name = 1 RETURNING id")

To retrieve more than one columns, just list the column names after RETURNING, e.g.

rows, err := db.Queryx("UPDATE mytable SET var_name = 0 WHERE var_name = 1 RETURNING id,var_name,other_columns")
for rows.Next() {
    //do something with the result
}

huangapple
  • 本文由 发表于 2017年8月12日 16:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/45648262.html
匿名

发表评论

匿名网友

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

确定