英文:
Passing String to Prepared Statement in Golang
问题
我理解你的问题是关于更新状态并且只在状态不同的情况下返回id的问题。
你的准备语句如下所示:
var theQuery = `UPDATE process SET status=$1 WHERE status!=$1 AND id=$2 RETURNING id`
然后,你使用以下代码调用它:
err = statement.QueryRow("set", 12).Scan(&id)
然后出现了以下错误:
runtime error: invalid memory address or nil pointer dereference
当你尝试使用以下代码时:
var theQuery = `UPDATE process SET status='$1' WHERE status!='$1' AND id=$2 RETURNING id`
它可以正常运行。然后,当你再次运行它时,你期望得到no rows
,但它仍然返回了id。看起来它仍然更新了行并忽略了status!='$1'
部分。
谢谢。
英文:
The idea is I want to update the status
and returning the id only if the status
is different.
So, I have a prepared statement like this:
var theQuery = `UPDATE process SET status=$1 WHERE status!=$1 AND id=$2 RETURNING id`
Then, I called it with this:
err = statement.QueryRow("set", 12).Scan(&id)
Then there is an error appear like this.
runtime error: invalid memory address or nil pointer dereference
When I tried:
var theQuery = `UPDATE process SET status='$1' WHERE status!='$1' AND id=$2 RETURNING id`
It runs. Then, when I run it again, I am expecting to get no rows
, but it still returning the id. It looked like it still updating the rows and ignored the status!='$1'
part.
Thank you
答案1
得分: 1
所以,我刚刚找到了解决方案。不再使用$1
两次,而是准备好的语句将接收3个参数:
var theQuery = `UPDATE process SET status=$1 WHERE status!=$2 AND id=$3 RETURNING id`
然后,我这样调用准备好的语句。
status := "set"
err = statement.QueryRow(status, status, 12).Scan(&id)
我知道这可能不是解决问题的最佳方法。但对我来说有效。
英文:
So, I just find the solution. Instead of using $1
twice, the prepared statement will received 3 arguments:
var theQuery = `UPDATE process SET status=$1 WHERE status!=$2 AND id=$3 RETURNING id`
Then, I call the prepared statement like this.
status := "set"
err = statement.QueryRow(status, status, 12).Scan(&id)
I know maybe this is not the best approach to solve the problem. But it worked for me.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论