简体   繁体   English

If-else语句中的While循环(Java)

[英]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. 我正在编写一个Java程序,当在另一个数据库中找到具有相同产品模型的记录时,它将使用新的详细信息更新本地数据库中的现有数据。 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. 我正在使用if-else语句来检查记录是否确实存在。 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. 但是,在添加while循环之后,我在if语句中添加了while循环,其中记录存在。 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. 似乎一旦进入if(rs.next())条件,就不会进入while循环。

Will anyone let me know what I'm doing wrong? 有人会让我知道我在做什么错吗? Is it possible to use a while loop inside an if-else statement? 是否可以在if-else语句中使用while循环? As usually it is used the other way around, if-else statement within the while loop. 通常,它与while循环中的if-else语句相反。

Any help will be greatly appreciated. 任何帮助将不胜感激。 Thank you. 谢谢。

You do not have to add a separate if statement while (rs.next()) { //CODE } 您不必while (rs.next()) { //CODE }添加单独的if语句。

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. 如果您调用next()2次,游标将向前移动2条记录,并且如果您只有一条记录用于查询,它将不会进入while循环。

CODE will execute only if there is a results remaining. 仅在结果剩余时才执行CODE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM