简体   繁体   English

准备好的语句 java 中的 OR 子句

[英]OR clause in prepared statement java

Can we use OR clause in a PreparedStatement using java?我们可以在使用 java 的 PreparedStatement 中使用 OR 子句吗?

PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");  
stmt.setString(1, "'MIKE' || 'ANDY'"); 
int i = stmt.executeUpdate();  
System.out.println(i + " records deleted");  

No. This is not raw text substitution and you can't drop in chunks of the query and expect them to get incorporated in. Each thing substituted for a placeholder gets sanitized, encoded, and quoted as a separate value.不。这不是原始文本替换,您不能放入查询的块中并期望它们被合并。每个替换占位符的东西都会被清理、编码和引用为单独的值。

But you can write it with 2 placeholders:但是您可以使用 2 个占位符来编写它:

PreparedStatement stmt=con.prepareStatement(
    “delete from emp where id in (?, ?)”);
stmt.setString(1,"MIKE”);
stmt.setString(2, “ANDY”);

If you have a lot of values in the IN clause an alternative is to put those values in a table and join to it.如果 IN 子句中有很多值,另一种方法是将这些值放在一个表中并加入它。

You can simply use two parameters.您可以简单地使用两个参数。

PreparedStatement stmt=con.prepareStatement("delete from emp where id=? or id=?");
stmt.setString(1,"ANDY");
stmt.setString(2,"MIKE");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM