escape % Wildcard in prepared statement

Viewed 45

The following code returns an error:

stmt, err := DBCon.Prepare("SELECT * FROM item WHERE market_hash_name LIKE '%?%' ")
handle_error(err)
res, err := stmt.Query(market_hash_name)

the error: 2022/07/09 19:57:56 http: panic serving <ip> sql: expected 0 arguments, got 1

this statement works:

stmt, err := DBCon.Prepare("SELECT * FROM item WHERE market_hash_name LIKE ? ")

How can I escape the %sign?

1 Answers

How can I escape the %sign?

The problem is not the percent sign, the problem is that ? is inside a string literal, which makes it a literal question mark and not a parameter placeholder. And because the statement does not recognize the literal question mark as a parameter placeholder it expects NO arguments, which is why the error says: expected 0 arguments.


To add % to the argument you have at least two options:

  1. Add the percent signs to the Go argument market_hash_name, e.g.
stmt.Query("%"+market_hash_name+"%")
  1. Concatenate the percent signs to the ? in the SQL string with
CONCAT('%', ?, '%')
Related