Вопрос

I'm trying to build a pay desk in a grocery store and my code actually performs what I intend for it to do, but for one thing.

After I ask the user to enter how many of an item they want, the product information is gathered and works fine, but when it's supposed to ask the user to enter product-ID for next product, the line is repeated and I get the following exception in my catch: "Illegal operation on empty result set". Again, all the calculations and everything is fine except for the repeating of that line. Any ideas on what might be the problem?

The output that is repeat is like this:

Enter product (or Exit):

ERROR1: Illegal operation on empty result set.

Enter product (or Exit):

And here's the code.

try {
  Class.forName("com.mysql.jdbc.Driver");
  String connection = "jdbc:mysql://myDB?";
  connection = connection + "user=xxx&password=xxxxxx";
  Connection conn = DriverManager.getConnection(connection);
  // MATA IN PRODUKTNUMMER
  System.out.println("\nEnter product (or Exit):");
  GroceryStore.input = GroceryStore.scan.nextLine();

  PreparedStatement stmt = conn.prepareStatement(
          "SELECT * "+
          "FROM Products "+
          "WHERE productNo = ?");
          stmt.setString(1, GroceryStore.input); 

          ResultSet rs = stmt.executeQuery();
          rs.next();

    pName = rs.getString("productName");
    System.out.println("Product: " + pName);

    // MATA IN ANTAL
    System.out.println("\nEnter amount:");
    GroceryStore.amount = GroceryStore.scan.nextInt();


    pPrice = rs.getDouble("productPrice");
    priceRounded = new BigDecimal(pPrice).setScale(2, BigDecimal.ROUND_FLOOR);
    amountRounded = new BigDecimal(GroceryStore.amount).setScale(0);
    priceRounded = priceRounded.multiply(amountRounded);
    GroceryStore.sum = GroceryStore.sum.add(priceRounded);

    inOut.output();  
    inOut.input();
    conn.close();
    }
    catch (Exception e) {
         System.out.println("ERROR1: " + e.getMessage());
    }
Это было полезно?

Решение 2

You haven't checked Whether your result set is empty or not before actually retriving values from Result set...

next() returns true if there is a data in the result set, false it there is not data at the a cursor position Place your code like this

While(rs.next())
{
    pName = rs.getString("productName");
    System.out.println("Product: " + pName);

    // MATA IN ANTAL
    System.out.println("\nEnter amount:");
    GroceryStore.amount = GroceryStore.scan.nextInt();


    pPrice = rs.getDouble("productPrice");
}

Другие советы

You are not checking whether your result set has any data or row in it.

ResultSet rs = stmt.executeQuery();
rs.next();
...
...

You should check whether your result is empty or having any row:

ResultSet rs = stmt.executeQuery();
if(rs.next()){
.....
your code
.....
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top