空结果集上的非法操作

时间:2013-02-28 10:47:08

标签: java exception operation

我正在尝试在杂货店建立一个付款台,而我的代码实际上执行了我打算做的事情,但仅举一例。

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

重复的输出如下:

  

输入产品(或退出):

     

错误1:空结果集上的非法操作。

     

输入产品(或退出):

这是代码。

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

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:2)

在从Result set ...

中实际检索值之前,您尚未检查结果集是否为空 如果结果集中有数据,则

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