Reputation: 635
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?
Upvotes: 0
Views: 5503
Reputation: 136
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.
Upvotes: 4
Reputation: 290
Using printf
to construct queries is a bad idea, it opens you up to SQL injection.
See named parameters in the sql package.
Upvotes: 5