从特定的sql语句中获取true(1)或false(0)

时间:2015-01-26 22:47:56

标签: java mysql

我需要以下代码的帮助,并让它返回true或false值。任何和所有的帮助将不胜感激。

    public synchronized static boolean checkCompanyName(String companyName,
        Statement statement) {
    try {

        ResultSet res = statement
                .executeQuery("SELECT `companyName` FROM `companys` WHERE companyName = '"
                        + companyName + "';");
        boolean containsCompany = res.next();

        res.close();

        return containsCompany;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

3 个答案:

答案 0 :(得分:0)

尝试按照以下方式进行查询:

ResultSet res = statement.executeQuery("SELECT companyName FROM companys WHERE companyName = " + companyName);

或者你可以PreparedStatement,这比之前更好

答案 1 :(得分:0)

两条评论:

  1. 您只需要检查是否至少有一行符合您的条件,因此您可以使用.first()
  2. 您的代码容易受到SQL注入攻击。请阅读this以了解详情。
  3. 避免SQL注入attacs的最简单方法是使用prepared statements。因此,让我用一块石头打两只鸟,并用它们给你一个解决方案:

    /*
    Check if the company exists.
    Parameters:
      conn    -  The connection to your database
      company - The name of the company
    Returns:
      true if the company exists, false otherwise
    */
    public static boolean checkCompanyName(Connection conn, String company) {
        boolean ans = false;
        try(PreparedStatement ps = conn.prepareStatement(
                "select companyName from companies where companyName = ?"
            ) // The question mark is a place holder
        ) {
            ps.setString(1, company); // You set the value for each place holder
                                      // using setXXX() methods
            try(ResultSet rs = ps.executeQuery()) {
                ans = rs.first();
            } catch(SQLException e) {
                // Handle the exception here
            }
        } catch(SQLException e) {
            // Handle the exception here
        }
        return ans;
    }
    

    建议阅读:

答案 2 :(得分:0)

您应该使用PreparedStatement(为此目的将Connection传递给方法)。此外,您应该从ResultSet检索值并验证它与您的companyName匹配。像

这样的东西
static final String query = "SELECT `companyName` FROM "
    + "`companys` WHERE companyName = ?";

public synchronized static boolean checkCompanyName(String companyName,
        Connection conn) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(query);
        ps.setString(1, companyName);
        rs = ps.executeQuery();
        if (rs.next()) {
            String v = rs.getString(1);
            return v.equals(companyName);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
            }
        }
    }
    return false;
}