1

I've seen a very similar problem here, but I'm not certain what the pipes do in the command, and it didn't work for me anyway.

So, here's the code I've tried.

rows, err := db.Query(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel.%'"))

And even though, I have no idea what it's for, I also tried with the pipes.

rows, err := db.Query(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel. || %'"))

So, what it should be doing, is matching anything in that column that starts with camel., so camel.*

The error I'm getting for both examples is

pq: syntax error at or near "("

So i'm guessing for some reason it's passing in more of that line as the command than I would like....maybe a quote problem? I've tried a few other things, but nothing has worked. Any help is appreciated.

Community
  • 1
  • 1
trueCamelType
  • 2,198
  • 5
  • 39
  • 76

3 Answers3

5

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

mt.Println(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel%'"))

//Output:
//SELECT * FROM mytable WHERE mycolumn LIKE 'camel%!'(MISSING)
//Ofc postgres will complain

You do not need fmt.Sprintf in this case.

rows, err := db.Query("SELECT * FROM mytable WHERE mycolumn LIKE 'camel.%'")

works fine.

But if you really need to use fmt.Sprintf you must escape '%' with '%%'

rows, err := db.Query(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel.%%'"))
Community
  • 1
  • 1
Darigaaz
  • 1,414
  • 10
  • 11
  • When I use either of those examples, I get ```pq: operator does not exist: inet ~~ unknown```. Looking into that error now, just figured I'd respond first. – trueCamelType Jun 02 '16 at 22:10
  • ok, I needed to type cast ```mycolumn```. So changing the query to ```SELECT * FROM mytable WHERE mycolumn::text LIKE 'camel.%'``` – trueCamelType Jun 02 '16 at 22:13
  • 1
    Come on... Do NOT use any formatting to build a query string! Flashbacks of the old days of SQL Injection come back to haunt us. Use your SQL package's parameter assignments when running the query, so they are properly escaped. `rows, err := db.Query("SELECT * FROM mytable WHERE mycolumn LIKE (?)", "camel.%")` – eduncan911 Jun 03 '16 at 14:00
  • You are right, but question was about something else) – Darigaaz Jun 03 '16 at 16:38
0

You should use Query using prepared statements for security, you can concat using CONCAT :

rows, err := db.Query("SELECT * FROM mytable WHERE mycolumn LIKE CONCAT(?, '%')", camel)

Hope it helps!

QuarK
  • 2,306
  • 1
  • 20
  • 24
0

you can use the LIKE '%' || camel. || '%'

Medone
  • 127
  • 1
  • 3
  • 11