我正在尝试构建一个 Mysql 查询,其中 where 条件有一个字符串。我无法构建查询。
我已经尝试过这段代码。
package doubts;
public class Doubts {
public static void main(String[] args) {
String sb = "select * from a where b = ";
String a = "abc";
System.out.println(sb+a);
}
}
我能够使用上述代码构建的查询是:
select * from a where b = abc
我想要:
select * from a where b = "abc"
我希望能找到解决这个问题的方法。
最佳答案
就像 deHaar 和 Arnaud 已经写过的那样:
将 a
放在双引号中。
例如:
public static void main(String[] args) {
String sb = "select * from a where b = ";
String a = "\"abc\"";
System.out.println(sb+a);
}
更好:在数据库上执行此查询时,使用 PreparedStatement
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(...);) {
try (PreparedStatement pstmt = conn.prepareStatement("select * from a where b = ?");) {
pstmt.setString(1, "abc");
try (ResultSet rs = pstmt.executeQuery();) {
...
}
}
}
}
关于java - Mysql查询组装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56002993/