有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对空结果集的非法操作

我正试图在一家杂货店建立一个付款台,我的代码实际上执行了我想要它做的事情,但有一件事

在我要求用户输入他们想要的商品数量后,产品信息会被收集起来并正常工作,但当我要求用户输入下一个产品的产品ID时,这行代码会重复,我的捕获中出现以下异常:“对空结果集的非法操作”。再说一遍,所有的计算和一切都很好,除了重复那句话。有什么问题吗

重复的输出如下:

Enter product (or Exit):

ERROR1: Illegal operation on empty result set.

Enter product (or Exit):

这是代码

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) 个答案

  1. # 1 楼答案

    您没有检查结果集中是否有任何数据或行

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

    您应该检查结果是否为空或是否有任何行:

    ResultSet rs = stmt.executeQuery();
    if(rs.next()){
    .....
    your code
    .....
    }
    
  2. # 2 楼答案

    在实际从结果集中检索值之前,尚未检查结果集是否为空

    如果结果集中有数据,next()返回true;如果光标位置没有数据,则返回false 像这样放置代码

    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");
    }