【问题标题】:How to add multiple rows from JTable to MySQL database如何将多行从 JTable 添加到 MySQL 数据库
【发布时间】:2021-12-19 17:11:54
【问题描述】:

我一直在尝试将 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) {
          
          }

【问题讨论】:

  • 为什么要将行数设置为零?
  • @halfer 道歉。我是新手,对规则不太熟悉。我会确保在可预见的未来不会发生这种情况。
  • 谢谢约书亚! Stack Overflow 的理念是问题(及其答案)变得几乎像文档一样,因此首选简洁的技术写作 - 理想情况下尽可能针对广泛/一般情况量身定制。

标签: java mysql netbeans


【解决方案1】:

这行代码

tblmodel.setRowCount(0)

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

【讨论】:

  • 保存完成后我用它来重置JTable。
  • reset a table 意味着清除它。这就是你想要的吗?
  • 是的,我删除了 tblmodel.setRowCount (0) 并且它工作得非常好,但是我现在无法清除 jTable,因为这个函数曾经清除它。
  • 我不确定你什么时候想清除它,但是在你退出 for 循环之后清除它怎么样?
猜你喜欢
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
相关资源
最近更新 更多