2013-03-24 69 views
1

我想通过使用jtable数据更新MySql。我有6列(周期,星期一,星期二,星期四,星期五,星期五)在MySQL中。在jtable中我有和mysql一样的表。在MySQL中,我已经给出了期间值(1,2,3,4)。更新Jtable值到MySql表

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+"'"); 
    } 
    } 

This is the jTable

This is the MySql table.It should be the same as jTable

+0

我想让我的jTable和MySql数据一致。 – ramindusn 2013-03-24 14:19:42

回答

2
  • 请阅读Oracle Tutorial about JTable

  • 表在数据库中有similair结构的JTable在Swing,

  • (之前没有关于代码想法)各内部结果集循环返回只有一行,用相同的顺序如在SQL查询定义,

  • 创建阵列从数据库行填补数据和添加此arraya作为new row to the XxxTableModel

  • 搜索ResultSetTableModelTableFromDatabase

0

此代码应为所有工作表(不管有多少行或列的JTable怎么了)。只需将'TableName'替换为您希望在mysql中更新的表。

这里'不'是表的主键。

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

      } 

     }