fmt.Sprintf 更新数据库

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

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.

huangapple
  • 本文由 发表于 2022年12月27日 21:02:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/74929624.html
匿名

发表评论

匿名网友

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

确定