java - 在 Java 中进行销售后减少 MySQL 数据库中的库存数量

标签 java mysql

以下代码是我在销售后用新的剩余库存数量更新数据库的方法。

在我的表单中,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);。帮我解决这个错误。

enter image description here

最佳答案

替换这一行


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/

相关文章:

php - Laravel save() 方法后无法检索自定义 id 主键

java - GridView 行为不正确

php - mysql 数组到字符串的转换

MySql 不允许在表中添加值 -> ERROR 1054

mysql - 使用相同的计算值更新同一查询中的两个字段

mysql - SQL MACH() AGAINST() 关键字长度

java - Eclipse侦察员 hibernate

java - apache commons FileUtils.copyFile 错误系统资源不足,无法完成请求

java - 我们使用 JMS 而不是使用 REST TEMPLATE 来交换信息有什么优势?

java - 使用动态数据源进行动态数据源路由