// Use case 1.
String authorName = "Wei She";
String query = "SELECT * FROM articles WHERE authors LIKE %?%";
PreparedStatement getAuthors = newConn.prepareStatement(query);
getAuthors.setString(1, authorName);
ResultSet resultSet = getAuthors.executeQuery();
while (resultSet.next()) {
String authors = resultSet.getString("authors");
System.out.println(authors);
}
下面是我的代码的一个子集。数据已经在我的本地MySQL数据库中了。连接代码的其余部分已经存在。
我的问题是:我应该如何格式化Java代码中的%?%部分?我是不是漏掉了什么?以下是错误输出。
Exception in thread "main" java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/%'Wei She'/%' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:975)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1025)
at src.TestSQLQuery.main(TestSQLQuery.java:34)
我在MySQL工作台中使用了一个类似的查询: SELECT * FROM作者喜欢'%Wei She%‘的文章;
上面的查询在Workbench中运行良好,并返回与其他作者的多个条目以及"Wei“。
发布于 2018-09-11 07:47:34
%?%
无效。您只需要使用?
,并将值中的%
符号传递给PreparedStatement
String query = "SELECT * FROM articles WHERE authors LIKE ?";
PreparedStatement getAuthors = newConn.prepareStatement(query);
getAuthors.setString(1, "%" + authorName + "%");
https://stackoverflow.com/questions/52266723
复制相似问题