简体   繁体   English

如何检查Psql是否成功更新了Go中的记录

[英]How can I check whether Psql successfully updated the record in Go

I use this driver to communicate with psql from Go. 我使用这个驱动程序与Go的psql进行通信。 Now when I issue an update query, I have no possibility to know whether it actually updated anything (it can update 0 rows if such id is not present). 现在,当我发出更新查询时,我无法知道它是否实际更新了任何内容(如果不存在这样的id,它可以更新0行)。

_, err := Db.Query("UPDATE tags SET name=$1 WHERE id=1", name)

I tried to investigate err variable (in the way the doc suggests for Insert statement): 我试图调查错误的变量(就像文档建议的Insert语句一样):

if err == sql.ErrNoRows {
    ...
}

But even with non-existent id, err is still null. 但即使id不存在,错误仍然是空的。

I also tried to use QueryRow with returning clause: 我还尝试将QueryRow与return子句一起使用:

id := 0
err := Db.QueryRow("UPDATE tags SET name=$1 WHERE id=1 RETURNING id", name).Scan(&id)

But this one fails to scan &id when id=1 is not present in the database. 但是当数据库中不存在id = 1时,这个无法扫描&id。


So what is the canonical way to check whether my update updated anything? 那么检查我的更新是否更新的规范方法是什么?

Try using db.Exec() instead of db.Query() for queries that do not return results. 尝试将db.Exec()而不是db.Query()用于不返回结果的查询。 Instead of returning a sql.Rows object (which doesn't have a way to check how many rows were affected), it returns a sql.Result object, which has a method RowsAffected() (int64, error) . 它不返回一个sql.Rows对象(没有办法检查受影响的行数),而是返回一个sql.Result对象,它有一个方法RowsAffected() (int64, error) This returns the number of rows affected (inserted, deleted, updated) by any write operations in the query fed to the Exec() call. 这将返回由送入Exec()调用的查询中的任何写入操作影响(插入,删除,更新)的行数。

Note that if your query doesn't affect any rows directly, but only does so via a subquery, the rows affected by the subquery will not be counted as rows affected for that method call. 请注意,如果查询不直接影响任何行,但仅通过子查询影响,则受子查询影响的行将不会计为受该方法调用影响的行。

Also, as the method comment notes, this doesn't work for all database types, but I know for a fact it works with pq , as we're using that driver ourselves (and using the RowsAffected() method). 此外,正如方法注释所指出的那样,这并不适用于所有数据库类型,但我知道它适用于pq ,因为我们自己使用该驱动程序(并使用RowsAffected()方法)。

Reference links: 参考链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM