douzi1986
2017-11-07 10:06 阅读 775
已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongqian3750 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 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.

    点赞 评论 复制链接分享

相关推荐