0

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.

1
  • Why are you commenting out the logger output? That output is quite important. Commented Jun 21, 2016 at 1:53

1 Answer 1

1

You do not have to add a separate if statement while (rs.next()) { //CODE }

if you call next() 2 times, cursor will move 2 records forward and if you have only one record for the query, it will not go into the while loop.

CODE will execute only if there is a results remaining.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.