[英]JDBC ilike query java
JDBC successfully connected to PostgreSQL. But some ilike query still have problems. JDBC成功连接到PostgreSQL。但是一些类似的查询仍然有问题。 only 1 code is working.
只有 1 个代码有效。 I want the first and the third one to working properly.
我希望第一个和第三个能够正常工作。
--------------- not working -------------- 不工作
String ilikequery = "SELECT * FROM emp where ? iLIKE '%C%' ";
PreparedStatement ilikestatement = Main.connection.prepareStatement(ilikequery);
ilikestatement.setString(1,"name");
ResultSet resultSet = ilikestatement.executeQuery();
-------------- this one working, -------------- 这个工作,
String queryname = "Cowen";
String query = "select * from emp where name = ?";
PreparedStatement statement = Main.connection.prepareStatement(query);
statement.setString(1,queryname);
ResultSet resultSet = statement.executeQuery();
------------this one not working. -----------这个不工作。
String ilikequerywithparameter = "SELECT * FROM emp" + " where name iLIKE '%"+"?"+"%' ";
PreparedStatement ilikestatementpara = Main.connection.prepareStatement(ilikequerywithparameter);
ilikestatementpara.setString(1,"c");
ResultSet resultSet = ilikestatementpara.executeQuery();
The last code snippet have Exception error.最后一个代码片段有异常错误。
Exception in thread "main" org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns:
-------- this one is working. -------- 这个正在工作。
String simpleilikequery = "SELECT * FROM emp" + " WHERE name iLIKE '%C%'";
PreparedStatement simpleilikestatement = Main.connection.prepareStatement(simpleilikequery);
ResultSet resultSet = simpleilikestatement.executeQuery();
You need to pass the wildcards as part of the parameter, not the prepared statement:您需要将通配符作为参数的一部分传递,而不是准备好的语句:
String sql = "SELECT * FROM emp where name iLIKE ?";
PreparedStatement stmt = Main.connection.prepareStatement(ilikequerywithparameter);
stmt.setString(1,"%c%");
Or alternatively use concat()
in the SQL string if you don't want to (or can't) modify the parameter itself.或者,如果您不想(或不能)修改参数本身,也可以在 SQL 字符串中使用
concat()
。
String sql = "SELECT * FROM emp where name iLIKE concat('%', ?, '%')";
PreparedStatement stmt = Main.connection.prepareStatement(ilikequerywithparameter);
stmt.setString(1,"c");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.