// 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 Workbench中使用了类似的查询:SELECT * FROM文章,作者喜欢'%Wei She%';
上面的查询在Workbench中工作正常,并与其他作者以及“微社”一起返回多个条目。
答案 0 :(得分:1)
%?%
无效。您只需要使用?
并让%
登录传递给PreparedStatement
的值:
String query = "SELECT * FROM articles WHERE authors LIKE ?";
PreparedStatement getAuthors = newConn.prepareStatement(query);
getAuthors.setString(1, "%" + authorName + "%");