-1

I have an SQL query that looks like this:

SELECT name FROM sessions WHERE name ILIKE 'org_name.%';

but I'm actually interested in replacing 'org_name' with format string (%s).
I was trying to do something like this:

query := fmt.Sprintf("SELECT name FROM sessions WHERE name ILIKE '%s.%'", "org_name2")

but go seems to not like it, since writing %' isn't valid as format string.
I know I can solve it with do it in that way:

orgName := "org_name2"
condition := fmt.Sprintf("%s", orgName) + ".%"
query := fmt.Sprintf("SELECT name FROM sessions WHERE name ILIKE '%s'", condition)


but, I'd rather not, since the variable here is solely the org_name.
Is there a solution for this?
Thanks!

Nyta
  • 557
  • 1
  • 7
  • 18

2 Answers2

12

As documented in the fmt package, a literal % can be represented by %% in a printf format string:

query := fmt.Sprintf("SELECT name FROM sessions WHERE name ILIKE '%s.%%'", orgName)

But be aware, you should NEVER, EVER build your SQL queries this way! You are potentially opening yourself for SQL injection attacks. Instead, you should pass parameterized arguments:

query := "SELECT name FROM sessions WHERE name ILIKE ?"
rows, err := db.Query(query, orgName + ".%")
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
1

In go it is just fmt.Printf("%s is how you write a %%", "This")

https://play.golang.org/p/RIJKRADYzCk

nzajt
  • 1,937
  • 1
  • 15
  • 16