以下SQL查询对从表中计数多个字段是否正确

时间:2018-07-05 08:28:52

标签: java mysql sql jdbc

Statement statement = conn.createStatement();
ResultSet rs1 = statement.executeQuery(
  "Select count(*) from user where username=? OR email=? OR phone=?"
);
int c = 0;

while (rs1.next()) {
    c++;
}

1 个答案:

答案 0 :(得分:3)

您的代码有一些问题:

  • 首先,您应该使用PreparedStatement,因为您使用的是?占位符
  • 您不应该使用while,因为您的查询仅返回一个结果

相反,您的代码应如下所示:

String query= "Select count(*) as cnt from user where username=? OR email=? OR phone=?";
try (PreparedStatement pstmt = conn.prepareStatement(query);) {
    pstmt.setString(1, username);
    pstmt.setString(2, email);
    pstmt.setString(3, phone);
    ResultSet rs1 = pstmt.executeQuery();
    long c = 0;
    if(rs1.next()){
        c = rs1.getLong("cnt");
    }
}