Home > Back-end >  escape % Wildcard in prepared statement
escape % Wildcard in prepared statement

Time:07-10

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?

CodePudding user response:

"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. That is why the error says expected 0 arguments, because there are no parameter placeholders in the SQL the statement expects no 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