mardi 21 juin 2016

While Loop inside an If-else statement (Java)

I'm writing a Java program in which it updates existing data in a local database with new details whenever a record that has the same product model in another database is found. If no record is found, it inserts a new record instead.

I'm using an if-else statement to check if record does exist or not. The current code works ONLY for a single record. I want it to keep on updating the local database as long as the product model in local database and in the other database exists.

Here's the code, I'm currently using:

public static void checkExist() {
    try {
        Statement stmt = conn.createStatement();
        int prod_qnty, prod_weight;
        float prod_price;

        String prod_model = "97801433"; //testing purposes

        ResultSet rs = stmt.executeQuery("SELECT * from products where products_model = " + prod_model );

        if (rs.next()){                
            //while (rs.next()) {    
                prod_qnty = rs.getInt("products_quantity");
                prod_price = rs.getFloat("products_price");
                prod_weight = rs.getInt("products_weight");

                System.out.println(prod_qnty + "t" + prod_price + "t" + prod_weight);

                updDB(prod_model, prod_qnty, prod_price, prod_weight);
            //}
        }
        else{
            insertDB(prod_model, prod_qnty, prod_price, prod_weight);
        }
        stmt.close();
    } catch (SQLException ex) {
        //Logger.getLogger(Check.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I've added a while loop within the if statement where record exists, however, after I've added the while loop. Now it can't even print out any record. It seems like once it goes inside the if (rs.next()) condition, it doesn't go inside the while loop.

Will anyone let me know what I'm doing wrong? Is it possible to use a while loop inside an if-else statement? As usually it is used the other way around, if-else statement within the while loop.

Any help will be greatly appreciated. Thank you.

Aucun commentaire:

Enregistrer un commentaire