eme*_*ieu 4 sql postgresql jpa jpql
我想使用LIKE和反斜杠来搜索一些名称。问题是Postgres将反斜杠理解为LIKE子句中的转义字符。我试图打开,standard_conforming_strings但没有帮助。
SELECT h.software_id
,h.software_name
FROM software h
WHERE software_name LIKE '%\%';
Run Code Online (Sandbox Code Playgroud)
该查询未显示任何内容,而我的软件名称为“ \”。
我听说有人提到过prepared statement。我使用Hibernate进行上述查询。
<persistence-unit name="policyPersistence" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/MyApp</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
</properties>
</persistence-unit>
Run Code Online (Sandbox Code Playgroud)
JPA
query.setParameter(1, "%" + searchCriteria.getSoftwareName() + "%");
Run Code Online (Sandbox Code Playgroud)
但是Postgres无法正确转义反斜杠。
如何解决?
与常规字符串文字不同,反斜杠确实充当转义符,更改standard_conforming_strings并不会改变它。
为了能够搜索a %或_using LIKE,可以使用以下escape子句:where x like '%#_' escape '#'将该字符定义#为类似条件的转义字符。转义字符后的任何字符都不会被解释为通配符。因此,like '%#_' escape '#'搜索以下划线结尾的值。
反斜杠是默认的转义字符,因此未指定escape子句与指定相同escape '\' (此行为由SQL标准定义)。
因此,您需要使用:
select *
from stuff.foo
where software_name like '%\%' escape '#'
Run Code Online (Sandbox Code Playgroud)
防止Postgres \用作转义字符。唯一的其他方法是使用来转义反斜杠'%\\%'(请注意:此处仅两个反斜杠,而不是TimoSta建议的四个)。
这是Postgres手册的链接:http :
//www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |