以下代码是我在销售后用新的剩余库存数量更新数据库的方法。
在我的表单中,tablesale 具有动态行。表示用户可以根据需要添加 1 个或多个。
所以我使用 for 循环获取当前表行并从 tablesale 中获取相关的 ItemID 并在 db 中搜索它,最后减少销售数量并将结果更新到数据库。
我的代码;
//redusing stock in db
for(int rcount=0;rcount<=tableSale.getRowCount();rcount++){
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");
}
}
但是代码抛出如下异常;
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
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:1009)
at com.bit.project.Newsale.access$1300(Newsale.java:57)
at com.bit.project.Newsale$16.actionPerformed(Newsale.java:651)
第 1009 行是 String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);
。帮我解决这个错误。
最佳答案
替换这一行
for(int rcount=0;rcount<=tableSale.getRowCount();rcount++){
有了这个
for(int rcount=0;rcount<tableSale.getRowCount();rcount++){
由于索引从 0 开始计数,如果行数为 1,则最大索引将为 0。它会在索引 1 上崩溃,这将解决此问题。
好的,上面的问题是有效的,另一件事是
rcount = tableSale.getRowCount();
rcount 是你的循环变量。你为什么要分配它表行数。行数始终为 max index+1 t 将始终导致索引超出范围。删除此行,然后检查。
关于java - 在 Java 中进行销售后减少 MySQL 数据库中的库存数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32155147/