简体   繁体   English

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

[英]How to add multiple rows from JTable to MySQL Database

I have been trying to add multiple rows from JTable to my MySQL Database, but only the first row is registered and not the rest.我一直在尝试将 JTable 中的多行添加到我的 MySQL 数据库中,但只注册了第一行,而没有注册其余行。 Here's my code.这是我的代码。 Do help.帮忙。 Thanks!谢谢!

This is a bit urgent, so it would be better if someone can respond asap.这有点紧急,所以如果有人能尽快回复就更好了。 Thanks again!再次感谢!

 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) {
          
          }

This line of code这行代码

tblmodel.setRowCount(0)

is causing it to break out of the loop after the first iteration.导致它在第一次迭代后跳出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM