netbeans 如何从JTable添加多行到MySQL数据库

jtoj6r0c  于 2022-11-10  发布在  Mysql
关注(0)|答案(1)|浏览(146)

我一直在尝试从JTable向MySQL数据库添加多行,但只注册了第一行,其余的都没有注册。
下面是我的代码:

DefaultTableModel tblmodel= (DefaultTableModel) jTable1.getModel();

  if (tblmodel.getRowCount()==0)
  {
      JOptionPane.showMessageDialog(this, "Table is Empty");
      }
  else {

      try
      {
          Class.forName("com.mysql.jdbc.Driver");

          Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","123456");

      for (int i=0; i<tblmodel.getRowCount(); i++)
      {
          String pid = (String)jTable1.getValueAt(i, 0);
    String pname = (String)jTable1.getValueAt(i, 1);
    int price = (int)jTable1.getValueAt(i, 2);
    int qty = (int)jTable1.getValueAt(i, 3);
    int tprice = (int)jTable1.getValueAt(i, 4);

    String query = "Insert into invoice(product_id, product_name, price,quantity, total_price) values (?,?,?,?,?)";
 PreparedStatement ps;
    ps = con.prepareStatement(query);

     ps.setString(1, pid);
    ps.setString(2, pname);
    ps.setInt(3, price);
    ps.setInt(4, qty);
    ps.setInt(5, tprice);
          ps.execute();
          JOptionPane.showMessageDialog(this , "Data added Successfully");
          tblmodel.setRowCount(0);

      }
      } catch (Exception e) {

          }
hl0ma9xz

hl0ma9xz1#

这行程式码

tblmodel.setRowCount(0)

导致它在第一次迭代后跳出循环。

相关问题