Bipin Khatiwada
Bipin Khatiwada

Reputation: 21

Is the following SQL query correct for counting the multiple fields from table

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++;
}

Upvotes: 0

Views: 53

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

Your code have some issues :

  • First you should use PreparedStatement because you are using ? placeholder
  • You should not using while because your query return only one result

Instead your code should look like :

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");
    }
}

Upvotes: 3

Related Questions