Credits

Monday, July 11, 2011

Java Programming to Edit a Database Record

Editing an SQL record is possible in Java only if we have the connection and allowed an action event on our Edit (formerly Update button in our previous post). 

If the Edit button is selected, we deactivate our Add and Delete button to make the updating exclusive. After a click on Update button,  other buttons become visible and active.
We next make sure that the new updates are reflected in our table. The program below shows this procedure.


[+/-] show/hide


private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
if(btnUpdate.getText().equalsIgnoreCase("Edit")) {
this.btnDelete.setEnabled(false);
this.btnAdd.setEnabled(false);
// this.btnExit.setEnabled(false);
btnUpdate.setText("Update");


} else {

SetConnection conn = new SetConnection();
Connection connect = SetConnection.conn;
Statement statement;

int row = tblComposer.getSelectedRow();


String query = "UPDATE composer SET composerlastname='"+txtLname.getText()+
"',composerfirstname='"+txtFname.getText()+
"' WHERE composerID = '"+txtComID.getText()+"'";
//confirm update

int result = JOptionPane.showConfirmDialog(getContentPane(),
"Are you sure you want to update Composition ID "+txtComID.getText()+" ?","Confirm",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);

if(result == JOptionPane.YES_OPTION){
statement = connect.createStatement();
statement.executeUpdate(query);
composer();
}

//this.btnExit.setEnabled(true);
this.btnDelete.setEnabled(true);
this.btnAdd.setEnabled(true);
btnUpdate.setText("Update");

}// for if else condition
} catch (Exception e) {
JOptionPane.showMessageDialog(getContentPane(),"Error: "+e,
"Error Message",JOptionPane.ERROR_MESSAGE);
}

}

AddThis