英文:
fmt.Sprintf update database
问题
我正在尝试将一个字符串连接到更新数据库的操作中,但是我无法使用sprinf %s来捕获值。
如果email.Event == "dropped" || email.Event == "bounce" || email.Event == "deferred",则执行以下操作:
- 将email.Reason赋值给email.Reason
- 将email.Reason赋值给reason变量
- 将email.SgMessageId赋值给sgID变量
然后,使用以下代码来生成更新数据库的字符串:
var teste = fmt.Sprintf("update email set erro = concat(erro,' ',%s) where id_sendgrid=%s", reason, sgID)
fmt.Println(teste)
但是,我无法获取这部分的值:(error,' ' %s)。在我的控制台中出现了以下错误:
update email set error = concat(error,' ',,) + where id_sendgrid=14c5d75ce93
请注意,这段代码中的错误是由于未提供要连接的第二个字符串值导致的。你需要提供一个有效的字符串值来替代这个错误。
英文:
I'm trying to concatenate a string to update my database, but I'm not able to capture the values with sprinf %s
if email.Event == "dropped" || email.Event == "bounce" || email.Event == "deferred" {
email.Reason = email.Reason
var reason = email.Reason
var sgID = email.SgMessageId
var teste = fmt.Sprintf("update email set erro = concat(erro,' ',%s) where id_sendgrid=%s", reason, sgID)
fmt.Println(teste)
_, err := h.DB.Exec(teste)
if err != nil {
log.Fatal("Erro ao realizar upload no email com evento ERROR")
}
fmt.Println(email.Reason, email.SgMessageId, email.Response)
}
I can capture the id_sendgrid value, but I can't get the value of this part here --> (error,' ' %s)
this error appears in my console:
update email set error = concat(error,' ',) + where id_sendgrid=14c5d75ce93
答案1
得分: 2
不要使用Sprintf来构建数据库查询,而是使用参数化查询:
_, err := h.DB.Exec(`update email set erro = concat(erro, ' ', $1) where id_sendgrid = $2`,
reason, sgID)
$1
、$2
等会自动被Exec的附加参数替换。
英文:
Do not use Sprintf to build database queries. Use parameterized queries instead:
_, err := h.DB.Exec(`update email set erro = concat(erro, ' ', $1) where id_sendgrid = $2`,
reason, sgID)
$1
, $2
and so forth are automatically replaced by the additional arguments to Exec.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论