2013-03-24 51 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); 
       } 

      } 

     }