在准备的语句中转义百分号(%)通配符。

huangapple go评论94阅读模式
英文:

escape % Wildcard in prepared statement

问题

以下是翻译好的内容:

以下代码返回一个错误:

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

错误信息为:
2022/07/09 19:57:56 http: panic serving <ip> sql: expected 0 arguments, got 1

以下语句是正确的:

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

如何转义百分号(%)符号?

英文:

The following code returns an error:

stmt, err := DBCon.Prepare(&quot;SELECT * FROM item WHERE market_hash_name LIKE &#39;%?%&#39; &quot;)
handle_error(err)
res, err := stmt.Query(market_hash_name)

the error:
2022/07/09 19:57:56 http: panic serving &lt;ip&gt; sql: expected 0 arguments, got 1

this statement works:

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

How can I escape the %sign?

答案1

得分: 2

如何转义百分号(%)?

问题不在于百分号,问题在于?位于字符串字面量中,这使得它成为一个字面上的问号,而不是参数占位符。由于语句不将字面上的问号识别为参数占位符,它期望没有参数,这就是为什么错误消息显示为“expected 0 arguments”。

要将百分号(%)添加到参数中,你至少有两个选项:

  1. 将百分号(%)添加到Go参数market_hash_name中,例如:
stmt.Query("%" + market_hash_name + "%")
  1. 使用SQL字符串将百分号(%)与?连接起来,例如:
CONCAT('%', ?, '%')
英文:

> 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(&quot;%&quot;+market_hash_name+&quot;%&quot;)
  1. Concatenate the percent signs to the ? in the SQL string with
CONCAT(&#39;%&#39;, ?, &#39;%&#39;)

huangapple
  • 本文由 发表于 2022年7月10日 04:10:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/72924302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定