Update Record JDBC Example with GUI

After inserting and deleting records, let us make one more program that updates the salary of a record. In this program, GUI environment is used to take employee ID and display the result. The output is planned to display the particulars like employee id, name, old salary and new salary after updating and the amount of salary incremented. TextField is used to take input of ID and TextArea to display the result.

import java.sql.*;     
import java.awt.*;
import java.awt.event.*;

public class UpdateRecord extends Frame implements ActionListener   
  TextField inputField;
  TextArea outputArea;

  public UpdateRecord()                    		// GUI creation  
    setLayout(new BorderLayout(0, 10));
    inputField = new TextField(15);
    outputArea = new TextArea(10, 50);


    add(inputField, "North");
    add(outputArea, "Center");
    setTitle("GUI with JDBC");
    setSize(300, 200);
  public void actionPerformed(ActionEvent e)
    int num = Integer.parseInt(inputField.getText());
      Connection con = DriverManager.getConnection("jdbc:odbc:snrao","scott","tiger");
      Statement stmt = con.createStatement();
                                                  //  to get the old salary from database of a specified record
      ResultSet res;
      res = stmt.executeQuery("select * from Employee where empid = "  + num);

      String name = res.getString(2);
      double oldSal = res.getDouble(3);
                                                  //  update the salary in the database by Rs.500
      stmt.executeUpdate("Update Employee set empsal = empsal + 500 where empid = " + num);
                  				 //  to get the new salary from database
      res = stmt.executeQuery( "select * from Employee where empid = " + num);
      double newSal = res.getDouble(3);
                                                 //  to display the old and new salary
      outputArea.append("Employee ID Number: " + num + "\nOLD SALARY Rs.: " + oldSal + "\nNEW SALARY Rs.: " + newSal + "\nIncreased Salary is Rs." + (newSal-oldSal));

      res.close();  stmt.close();  con.close();
     catch(Exception e1)
        System.err.println("Error in the database access: " + e1);
   public static void main(String args[])
     new UpdateRecord();

Update Record JDBC

Even if one record exist, res.next() should be used as the record pointer by default placed above first record. The record pointer is moved to the first record with res.next() method. This is discussed in JDBC Select Records Example

Note 1: Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.

Note 2: To know how to use try-catch-finally with the above code, example program is available at JDBC Example – Create Table.

1 thought on “Update Record JDBC Example with GUI”

Leave a Comment

Your email address will not be published.