我有一個以jframe形式的銷售表,用戶一次添加一行。數組索引溢出異常當嘗試更新Java數據庫中的Java
我想在表中減少數量柱減少使用inStock在MySQL表saleifo。
用於保存和打印按鈕的代碼段;
DefaultTableModel model = (DefaultTableModel) tableSale.getModel();
if(model.getRowCount()==0){
JOptionPane.showMessageDialog(null, "You have nothing to Print or Save ");
}else{
int save = JOptionPane.showConfirmDialog(null, "Do you really want to Save the Invoice Data ?","Save Confirmation",JOptionPane.YES_NO_OPTION);
if((save)==0){
try{
String saledate = ((JTextField)dayChooser.getDateEditor().getUiComponent()).getText();
String invoice = InvoiceNo_txt.getText();
String citems = countitems_txt.getText();
String tDis =totalDiscount_txt.getText();
String ntotal = NetTotal_txt.getText();
//setting data to saleinfo db table
try{
String sql = "Insert into saleinfo (SaleDate,InvoiceNo,TotalItems,TotalDiscount,NetTotal)values (?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, saledate);
pst.setString(2, invoice);
pst.setString(3, citems);
pst.setString(4, tDis);
pst.setString(5, ntotal);
pst.execute();
}catch(Exception e){
}
//redusing stock in db
int rcount = tableSale.getRowCount();
String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);
String sql0= "select * from druginfo where ItemID=?";
pst0=conn.prepareStatement(sql0);
pst0.setString(1, idsale);
rs0= pst0.executeQuery();
if(rs0.next()){
String instock = rs0.getString("InStock");
int nowstock=Integer.parseInt(instock);
int soldqty = (int) tableSale.getModel().getValueAt(rcount, 3);
int newstock = nowstock - soldqty;
System.out.println("new :"+newstock);
String sqlupdate= "update druginfo set InStock='"+newstock+"' where ItemID='"+idsale+"'";
pst=conn.prepareStatement(sqlupdate);
pst.execute();
System.out.println("Done");
}
但顯示ArrayIndexOutOfBoundsException
。
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
at java.util.Vector.elementAt(Vector.java:474) at java.util.Vector.elementAt(Vector.java:474)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at com.bit.project.Newsale.saveprint_btnActionPerformed(Newsale.java:1039)
at com.bit.project.Newsale.access$1300(Newsale.java:57)
at com.bit.project.Newsale$16.actionPerformed(Newsale.java:683)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
1039行是String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);
。
如何解決這個問題?
表有** 2 **行('rcount == 2'),所以'getValueAt(index,0)'對於索引'0'和'1'有效,但不是'2',這是你正在通過。 – Andreas
JDBC建議:在創建連接時提前準備所有語句。每次單擊按鈕時都無需創建準備好的語句。此外,準備好的更新語句也應該與'?'佔位符一起使用,而不是串聯字符串。 – RealSkeptic