我使用Java构建查询来搜索和获取记录,当使用值'(单引号)进行构建时(例如: New's )然后我没有得到任何结果。
以下是我设置值新的查询:
SELECT COUNT(1) FROM AGX_THERAPEUTIC_AREA T WHERE UPPER(T.THERAPEUTIC_NAME) LIKE ? ESCAPE \ OR UPPER(T.THERAPEUTIC_AREA_DESC) LIKE ? ESCAPE \
bind => [NEW'S%, NEW'S%]
以下是我处理单引号的方法:
public static String handleSingleQuote(String searchString) {
if ((searchString == null) || searchString.trim().equals("")) {
searchString = "";
}
searchString = searchString.trim();
int length = searchString.length();
StringBuffer searchBuffer = new StringBuffer();
for (int index = 0; index < length; index++) {
if (searchString.charAt(index) == '\'') {
searchBuffer.append("''");
} else {
searchBuffer.append(searchString.charAt(index));
}
} // end of for loop
searchString = searchBuffer.toString();
return (searchString);
}
答案 0 :(得分:4)
我使用Java构建了一个查询来搜索和获取记录,当使用值&#39; (单引号)(例如:New&#39; s)然后我没有得到任何结果。
然后你错误地构建它。听起来你正在使用字符串连接。 Never do that (见下文)。相反,请使用PreparedStatement
:
PreparedStatement ps = connection.prepareStatement(
"SELECT FOO FROM BAR WHERE COLUMN LIKE ? ESCAPE \\"
);
ps.setString("this 'has' single quotes");
ResultSet rs = ps.executeQuery();
您的JDBC连接器将确保正确发送字符串。
重新评论说你正在使用JPA:我不了解JPA,但this page表示它看起来像:
TypedQuery<Thingy> query = em.createQuery(
"SELECT FOO FROM BAR WHERE COLUMN LIKE :search ESCAPE \\",
Thingy.class
);
return query.setParameter("search", "this 'has' quotes").getSingleResult();
重新&#34; 永远不会那样做&#34;:
答案 1 :(得分:2)
你可以通过两个单引号来逃避它。
select 'Hello y''all!' from dual
答案 2 :(得分:0)
使用引号将其转义
SELECT 'New''s' AS text FROM DUAL;
答案 3 :(得分:0)
public static String handleSingleQuote(String searchString) {
if ((searchString == null) || searchString.trim().equals("")) {
searchString = "";
}
searchString = searchString.trim();
int length = searchString.length();
StringBuffer searchBuffer = new StringBuffer();
for (int index = 0; index < length; index++) {
if (searchString.charAt(index) == '\'') {
searchBuffer.append("\'");
} else {
searchBuffer.append(searchString.charAt(index));
}
} // end of for loop
searchString = searchBuffer.toString();
return (searchString);
}