How To Update All MySQL DataBase Values Using JTable In Java NetBeans
In this Java Tutorial we will see How To UPDATE DataBase Data With JTable Rows Values Using For Loop And addBatch Function On Button Click In Java NetBeans .
Project Source Code:
// function to get the connection
public Connection getConnection()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/s_t_d", "root", "");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return con;
}
// function to display data from mysql to Jtable
public void fillTable(){
Connection con = getConnection();
Statement ps;
ResultSet rs;
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
try {
ps = con.createStatement();
rs = ps.executeQuery("SELECT * FROM `student`");
while(rs.next()){// Id`, `FullName`, `Address`, `BirthDate
Object[] row = new Object[jTable1.getColumnCount()];
row[0] = rs.getInt("Id");
row[1] = rs.getString("FullName");
row[2] = rs.getString("Address");
row[3] = rs.getString("BirthDate");
model.addRow(row);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
// button update
private void jButtonUPdateAllActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = getConnection();
Statement st;
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
try {
st = con.createStatement();
for(int i = 0; i < model.getRowCount(); i++){
int id = Integer.valueOf(model.getValueAt(i, 0).toString());
String fn = model.getValueAt(i,1).toString();
String adr = model.getValueAt(i,2).toString();
String bdate = model.getValueAt(i,3).toString();
String updateQuery = "UPDATE `student` SET `FullName`='"+fn+"',`Address`='"+adr+"',`BirthDate`='"+bdate+"' WHERE `Id` = " +id;
st.addBatch(updateQuery);
}
int[] updatedRow = st.executeBatch();
System.out.println(updatedRow.length);
} catch (SQLException ex) {
Logger.getLogger(Update_All_MySQL_Data_Using_JTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
OutPut:
Download Projects Source Code
2 comments
commentsThe blog is sharing such a nice information.
ReplyMysql DBA Training