我的代码有什么问题,它表示数组超出范围索引-1

时间:2015-04-07 15:47:26

标签: java

try{
    String sql = "UPDATE Products SET ID=?, Category=?,Product=?,Price=?,InItem=?, OutItem=?, TimeOutItem=?, TotalStocks=?"
                      + "WHERE ID=? ";   
    pst = conn.prepareStatement(sql);
    pst.setString(0, ID.getText());
    pst.setString(1, Category.getSelectedItem().toString());
    pst.setString(2, Product.getText());
    pst.setString(3, Price.getText());
    pst.setString(4, Quantity.getText());
    pst.setString(5, out.getText());
    pst.setString(6, date.getDateFormatString().toString());
    pst.setString(7, Stocks.getText());

    int rowsUpdated = pst.executeUpdate();
    if(rowsUpdated > 0){
        UpdateJTable();
        JOptionPane.showMessageDialog(null, "Update");
    }
}catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

数组索引超出范围-1。我不知道为什么我的代码仍有错误请帮忙。

1 个答案:

答案 0 :(得分:2)

设置参数从1开始而不是从0开始

 pst.setString(1, ID.getText());
 pst.setString(2, Category.getSelectedItem().toString());

编辑:完整代码

try{
    String sql = "UPDATE Products SET Category=?,Product=?,Price=?,InItem=?, OutItem=?, TimeOutItem=?, TotalStocks=?"
                      + " WHERE ID=? ";   
    pst = conn.prepareStatement(sql);

    pst.setString(1, Category.getSelectedItem().toString());
    pst.setString(2, Product.getText());
    pst.setString(3, Price.getText());
    pst.setString(4, Quantity.getText());
    pst.setString(5, out.getText());
    pst.setString(6, date.getDateFormatString().toString());
    pst.setString(7, Stocks.getText());
    pst.setString(8, ID.getText());

    int rowsUpdated = pst.executeUpdate();
    if(rowsUpdated > 0){
        UpdateJTable();
        JOptionPane.showMessageDialog(null, "Update");
    }
}catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}