在java中捕获mysql语句时出错

时间:2017-05-05 02:15:57

标签: mysql

你好,所以我试图在sql语句中编写我自己的错误类型。在我的方法添加订单我想添加一些方法来阻止某人销售没有库存的产品。我的代码还没有这样做。我可以添加订单并更新库存量,但我还没有想出添加if语句的方法。

@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 

1 个答案:

答案 0 :(得分: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();