0

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
  • 1
    Why do you use %#[1]s instead of %[1]s? Commented Nov 7, 2017 at 10:18
  • What do you expect the flag # to do with strings s? What in the package documentation makes you believe # modifies the verb s? Commented Nov 7, 2017 at 10:20

2 Answers 2

5

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

See named parameters in the sql package.

Sign up to request clarification or add additional context in comments.

1 Comment

great tip, but doesn't answer the question
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.