空结果集上的非法操作

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

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

重复的输出是这样的:

输入产品(或退出):

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

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

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

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

您应该检查结果是空的还是有任何行:

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