2017-05-05 12 views
0

你好,我想編寫我自己的類型的錯誤在SQL語句捕捉。在我的方法添加訂單我想添加一些方法來阻止某人銷售沒有庫存的產品。我的下面的代碼還沒有這樣做。我可以添加訂單並更新庫存量,但我還沒有想出添加if語句的方法。在java中捕獲mysql語句的錯誤

@FXML 
public void AddOrder(ActionEvent event) { 

String orderID = orderBox.getText(); 
String customerID = customerBox.getText(); 
String productID = productBox.getText(); 
String amount = amountBox.getText(); 
// String cost = costBox.getText(); 
String date = dateBox.getText(); 
PreparedStatement sample; 

dc = new Database(); 

try { 
    c = dc.Connect(); 

    sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?"); 

    ResultSet rs = sample.executeQuery(); 

    while (rs.next()) { 

     Integer amount2 = rs.getInt("Amount"); 

     if (amount2 <= 0) { 

      System.out.println("No stock exists"); 

     } else { 

      query = c.prepareStatement(
        "INSERT INTO ordertable (orderID,customerID,productID,Amount,Date)VALUES(?,?,?,?,?)"); 
      update = c.prepareStatement("UPDATE inventory set stockAmount = stockAmount-? WHERE productID =?"); 
      update.setString(1, amount); 
      update.setString(2, productID); 
      update.execute(); 
      query.setString(1, orderID); 
      query.setString(2, customerID); 
      query.setString(3, productID); 
      query.setString(4, amount); 
      // query.setString(5, cost); 
      query.setString(5, date); 
      query.executeUpdate(); 
      // update.executeUpdate(); 
      Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "Saved"); 
      // closeConfirmation.showMessageDialog(this, "Saved"); 
      confirmation.show(); 
     } 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

orderBox.clear(); 
customerBox.clear(); 
productBox.clear(); 
amountBox.clear(); 

dateBox.clear(); 
loadDataFromDatabase(event); 
} 

下面是我得到

java.sql.SQLException: No value specified for parameter 1 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) 
    at 

回答

0

如果你只是有麻煩,因爲異常,檢查這些行錯誤:

sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?"); 

    ResultSet rs = sample.executeQuery(); 

查詢被定義爲接受productID的參數,但是在執行語句之前,您沒有給它一個值。您需要更改查詢,以便它不需要參數或爲參數分配值,如下所示:

sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?"); 
    sample.setString(1, productID); 
    ResultSet rs = sample.executeQuery(); 
+0

謝謝您的幫助。它現在編譯,我能夠執行代碼的其餘部分,但是如果庫存量達到0或更低,我仍然可以銷售商品。 –