Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

escape % Wildcard in prepared statement

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How can I escape the %sign?

>Solution :

"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('%', ?, '%')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading