douzi1986
2017-11-07 10:06
浏览 1.2k
已采纳

Golang Sprintf格式化字符串并多次使用

I try to generate a sql query using Sprintf() where I have to use the same variable two times

myStr := "test"
str := Sprintf("SELECT ... WHERE a = '%#[1]s' or b = '%#[1]s'", myStr)
fmt.Println(str)

This snippets outputs the expected string

SELECT ... WHERE a = 'test' or b = 'test'

but go vet says:

unrecognized printf flag for verb 's': '#' (vet)

And I am puzzled why. Switching the printf verb to v satisfies go vet but adds " around my string. And I honestly doesn't see a mistake in using %#[1]s.

Any thoughts?

图片转代码服务由CSDN问答提供 功能建议

我尝试使用 Sprintf()生成sql查询,而我必须使用 两次相同的变量

  myStr:=“ test” 
str:= Sprintf(“ SELECT ... WHERE a ='%#[1] s'或b ='  %#[1] s'“,myStr)
fmt.Println(str)
   
 
 

此摘要输出预期的字符串 < pre> SELECT ... ...其中a ='test'或b ='test'

,但是 go vet 说:

 动词's'无法识别的printf标志:'#'(vet)
   
 
 

我很困惑 为什么。 将printf动词切换为 v 可以满足 go vet ,但在字符串周围添加了。老实说,在使用%#[1] s

有什么想法吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongqian3750 2017-11-07 10:30
    已采纳

    Using printf to construct queries is a bad idea, it opens you up to SQL injection.

    See named parameters in the sql package.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongweicha6077 2017-11-08 16:14

    There is no # Sprintf flag for a string verb (the flag # is e.g. adding 0x for hex values: %#x). So remove it to make your go vet troubles disappear:

    myStr := "test"
    str := Sprintf("SELECT ... WHERE a = '%[1]s' or b = '%[1]s'", myStr)
    fmt.Println(str)
    

    But: If any part of your constructed query (myStr) comes from external input (i.e. user input), you really should follow Hein's advise and use named parameters.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题