【问题标题】:Illegal operation on empty result set [duplicate]对空结果集的非法操作[重复]
【发布时间】:2013-02-28 10:47:07
【问题描述】:

我正在尝试在杂货店建立一个付款台,而我的代码实际上执行了我想要它做的事情,但只是为了一件事。

在我要求用户输入他们想要的项目数量后,产品信息已收集并正常工作,但是当它应该要求用户输入下一个产品的产品 ID 时,重复该行并且我在我的捕获中得到以下异常:“对空结果集的非法操作”。同样,所有的计算和一切都很好,除了重复那条线。关于可能是什么问题的任何想法?

重复的输出是这样的:

输入产品(或退出):

ERROR1:对空结果集的非法操作。

输入产品(或退出):

这是代码。

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

【问题讨论】:

  • 您是否查看过您在搜索引擎中遇到的错误? stackoverflow.com/questions/5199250/…
  • “行重复”到底是什么意思?您应该使用来自rs.next() 的返回值来查看是否真的有 is 一行。
  • 哪一行重复了?
  • 用重复的行编辑。

标签: java exception operation


【解决方案1】:

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

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

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

ResultSet rs = stmt.executeQuery();
if(rs.next()){
.....
your code
.....
}

【讨论】:

    【解决方案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");
    }
    

    【讨论】:

    • 我在 Dbeaver 中执行查询,它完美地返回了结果,但是当我在 Java 代码中执行时,它给出了以下异常 [ERROR] Illegal operation on empty result set. 我还检查了 if(res!=null)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2016-04-30
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 2013-03-28
    相关资源
    最近更新 更多