英文:
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("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
得分: 2
如何转义百分号(%)?
问题不在于百分号,问题在于?
位于字符串字面量中,这使得它成为一个字面上的问号,而不是参数占位符。由于语句不将字面上的问号识别为参数占位符,它期望没有参数,这就是为什么错误消息显示为“expected 0 arguments”。
要将百分号(%)添加到参数中,你至少有两个选项:
- 将百分号(%)添加到Go参数
market_hash_name
中,例如:
stmt.Query("%" + market_hash_name + "%")
- 使用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:
- Add the percent signs to the Go argument
market_hash_name
, e.g.
stmt.Query("%"+market_hash_name+"%")
- Concatenate the percent signs to the
?
in the SQL string with
CONCAT('%', ?, '%')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论