首页 > 解决方案 > 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"

我想有一个解决这个问题的方法。

标签: javamysqlsql

解决方案


就像 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();) {
                ...
            }
        }
    }
}

推荐阅读