问题描述:

I want to compare each resultset from a database table, students, like this:

String gender = "";

rs = stat.executeQuery("SELECT gender FROM students;");

while (rs.next()) {

gender = rs.getString("Gender");

}

if (gender.equals("Male")) {

//not allowed

} else {

//allowed

}

however, the above code is not working.

网友答案:

You need to move your if else under your while loop as mentioned here:

    while(rs.next()){
       gender = rs.getString("Gender");
       if(gender.equals("Male")){
           //not allowed
       }else{
           //allowed  
       }
    }
网友答案:

Your if statements are outside while loop, where you obtaining each result. You probably would like to move your if-else statement into the loop.

网友答案:

I believe the problems are as follows:

1: remove the second-to-last semicolon from this statement rs = stat.executeQuery("SELECT gender FROM students;");

2: You call it 'gender' here: rs = stat.executeQuery("SELECT gender FROM students;"); But you call it 'Gender' here (change it to 'gender'). Gender and gender are two different words. gender = rs.getString("Gender");

网友答案:

I would suggest to alter the query(if your business case allows/makes sense here) to get only gender!=Male. This will reduce select statement execution and cut looping through unwanted values.

Then as suggested by others, move the logic into the while loop so that logic is applied to all values satisfying the condition.

相关阅读:
Top