简体   繁体   English

将Jtable值更新到MySql表

[英]Update Jtable values to MySql table

I want to update MySql by using jtable data. 我想通过使用jtable数据更新MySql。 I have 6 columns(periods,mon,tue,wed,thu,fri) in mysql. 我在mysql中有6列(句点,星期一,星期二,星期三,星期四,星期五)。 In jtable I have the same table as in mysql. 在jtable中,我有与mysql中相同的表。 In mysql I have already given periods values(1,2,3,4). 在mysql中,我已经给定了period值(1,2,3,4)。

Connection con = Driver.connect();
 for (int i = 0; i < 4; i++) {
   for(int j=1;j<=4;j++){
     Handler.setData(con, "update sem1 set mon='"+jTable1.getValueAt(i, 1)+"' where
     periods='"+j+"'" );
     Handler.setData(con, "update sem1 set tue='"+jTable1.getValueAt(i, 2)+"' where
     periods='"+j+"'" );
     Handler.setData(con, "update sem1 set wed='"+jTable1.getValueAt(i, 3)+"' where
     periods='"+j+"'" );
     Handler.setData(con, "update sem1 set thu='"+jTable1.getValueAt(i, 4)+"' where
     periods='"+j+"'" );
     Handler.setData(con, "update sem1 set Fri='"+jTable1.getValueAt(i, 5)+"' where
     periods='"+j+"'" );
     }
   }

这是jTable

这是MySql表,应该和jTable一样

  • please to read Oracle Tutorial about JTable , 请阅读有关JTable的Oracle教程

  • table in databases has the similair structure as JTable in Swing, 数据库中的表具有与Swing中的JTable类似的结构,

  • (no idea about code before) each of loops inside ResultSet returns only one row, with the same order as is defined in SQL Query, (之前不了解代码)ResultSet内部的每个循环仅返回一行,其顺序与SQL Query中定义的顺序相同,

  • create array fills data from database row and add this arraya as a new row to the XxxTableModel create array填充数据库行中的数据,并将该arraya作为新行添加到XxxTableModel

  • search for ResultSetTableModel or TableFromDatabase 搜索ResultSetTableModelTableFromDatabase

This Code should work for all tables(No matter how many rows or columns jTable has). 此代码应适用于所有表(无论jTable有多少行或列)。 Just Replace 'TableName' with the table you wish to update in mysql. 只需将“ TableName”替换为您要在mysql中更新的表即可。

Here 'No' is a Primary Key of the table. 这里的“否”是表的主键。

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

        String sd0 = null;
        for (int i = 1; i < dtm01.getColumnCount(); i++) {

            //  System.out.println(dtm01.getColumnName(1));
            for (int j = 0; j < dtm01.getRowCount(); j++) {
                try {
                    sd0 = dtm01.getValueAt(j, i).toString();

                    String sql = "update TableName set "+dtm01.getColumnName(i)+"='"+sd0+"' where No='"+dtm01.getValueAt(j, 0).toString()+"'";

                    pst=con.prepareStatement(sql);
                    pst.execute();
                    System.out.println(sql);
                } catch (SQLException ex) {
                    // Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }

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

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