java - Mysql查询组装
问题描述
我正在尝试构建一个 Mysql 查询,其中条件有一个字符串。我无法构建查询。
我试过这段代码。
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();) {
...
}
}
}
}
推荐阅读
- php - 提交带有特殊字符的表单时出现 403 禁止错误
- javascript - 页面加载时表单中的随机文本
- struts2 - 使用离子原生高级 http 时会话 Cookie 丢失
- php - preg_replace 使第一个字符大写而不使用像 ucwords() 这样的内置函数
- c++ - 运行搜索数组
- rabbitmq - Rabbitmq 无需重启即可重新加载/刷新新证书
- mongodb - 在特定时间执行多个查询时,我的 MongoDB CPU 使用率变为 100%
- java - Spring boot - Proguard - ant jar 打包:org.springframework.beans.factory.BeanDefinitionStoreException:
- android - 从频道 url 中提取 youtube 频道 ID - android
- ruby-on-rails - nil:NilClass 的未定义方法“humanize”