Java 如何在 JDBC 中使用类似 MySQL 的运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6599950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:06:20  来源:igfitidea点击:

How to use MySQL like operator in JDBC?

javamysqljdbc

提问by Sheeyla

I have the following syntax in my code, but it is not working when I am trying to use the LIKEoperator in JDBC. It works fine in this way, when it is just equal:

我的代码中有以下语法,但是当我尝试LIKE在 JDBC 中使用运算符时它不起作用。当它相等时,它以这种方式工作正常:

ResultSet resultSet = statement.executeQuery("SELECT * 
                                                FROM drawings 
                                               WHERE name = '"+ DT +"'");

But if I want to use the LIKEoperator to search as a wildcard, I keep getting the error saying that "%" is not a valid character. How I can correctly use the LIKE operator?

但是,如果我想使用LIKE运算符作为通配符进行搜索,则会不断收到错误消息,指出“%”不是有效字符。如何正确使用 LIKE 运算符?

采纳答案by BalusC

From the comments:

来自评论:

query=("SELECT * FROM drawings WHERE name LIKE '"%DT%"'");
query=("SELECT * FROM drawings WHERE name LIKE '"%DT%"'");

This does not compile. Assuming that DTis a variable, then it should rather look like

这不编译。假设这DT是一个变量,那么它应该看起来像

query = "SELECT * FROM drawings WHERE name LIKE '%" + DT + "%'";

(pay attention to the syntax highlighting, the %has to be part of the SQL string!)

(注意语法高亮,%必须是 SQL 字符串的一部分!)

However, concatenating user-controlled string variables like that in a SQL query puts doors wideopen for successful SQL injectionattacks. Learnhow to use PreparedStatementand use it instead.

然而,在SQL查询看跌门串联那样的用户控制的字符串变量打开成功的SQL注入攻击了解如何使用PreparedStatement和使用它。

String sql = "SELECT * FROM drawings WHERE name LIKE ?";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "%" + DT + "%");
resultSet = preparedStatement.executeQuery();
// ...