[英]Using '%' as a wild card character in a parameter in SQL with Java
So in my program I have: 所以在我的课程中我有:
private static final String GET_USERS_BY_PARAMS = "select * from user t "
+ "where t.id like %?% "
+ "AND t.name LIKE %?% "
+ "AND t.location LIKE %?% "
+ "AND t.telephone LIKE %?% ";
All of the parameters given above are stored as varchar in the database. 上面给出的所有参数都作为varchar存储在数据库中。
However when I run the following: 但是当我运行以下内容时:
statement = connection.prepareStatement(GET_USERS_BY_SEARCH_PARAMS);
statement.setString(1, userID);
statement.setString(2, name);
statement.setString(3, location);
statement.setString(4, telephone());
rs = statement.executeQuery();
I get a SQL exception stating that there was an invalid character. 我得到一个SQL异常,说明存在无效字符。 The application throws the error on the executeQuery, so setting the params isn't an issue.
应用程序在executeQuery上抛出错误,因此设置params不是问题。 I was wondering if this was down to using the % symbols, whihc I included so that you could search without having to input the exact user ID, name, or etc.
我想知道这是否归结为使用%符号,我包括在内,这样您就可以搜索而无需输入确切的用户ID,名称等。
Thanks for any help in advance! 在此先感谢您的帮助!
The wildcard has to be part of the value passed to the prepared statement. 通配符必须是传递给预准备语句的值的一部分。 So you need something like this:
所以你需要这样的东西:
private static final String GET_USERS_BY_PARAMS = "select * from user t "
+ "where t.id like ? "
+ "AND t.name LIKE ? "
+ "AND t.location LIKE ? "
+ "AND t.telephone LIKE ? ";
statement = connection.prepareStatement(GET_USERS_BY_SEARCH_PARAMS);
statement.setString(1, "%" + userID + "%");
statement.setString(2, "%" + name + "%");
statement.setString(3, "%" + location + "%");
statement.setString(4, "%" + telephone() + "%");
Btw: what datatype is user.id
? 顺便说一句:
user.id
数据类型是什么?
If that is a numeric value, LIKE won't work correctly. 如果这是一个数值,LIKE将无法正常工作。 You should probably explictely cast the ID to a character value instead:
where to_char(t.id) like ?
您可能应该明确地将ID转换为字符值:
where to_char(t.id) like ?
use CONCAT
function,it will works,like this: LIKE CONCAT('%', ?, '%')
使用
CONCAT
函数,它会工作,如下所示: LIKE CONCAT('%', ?, '%')
or also you can use LIKE ('%' || ? || '%')
或者你也可以使用
LIKE ('%' || ? || '%')
您可以使用连接运算符编写
LIKE ('%' || ? || '%')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.