Reputation: 53
I want to update MySql by using jtable data. I have 6 columns(periods,mon,tue,wed,thu,fri) in mysql. In jtable I have the same table as in mysql. In mysql I have already given periods values(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+"'" );
}
}
Upvotes: 1
Views: 2461
Reputation: 287
This Code should work for all tables(No matter how many rows or columns jTable has). Just Replace 'TableName' with the table you wish to update in 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);
}
}
}
Upvotes: 0
Reputation: 109813
please to read Oracle Tutorial about JTable,
table in databases has the similair structure as JTable in Swing,
(no idea about code before) each of loops inside ResultSet returns only one row, with the same order as is defined in SQL Query,
create array fills data from database row and add this arraya as a new row to the XxxTableModel
search for ResultSetTableModel
or TableFromDatabase
Upvotes: 2