UNIT-5 JDBC CRUD operations using Java Event handling: Two event handling mechanisms; delegation event model; event classes; source of events; event listener interface Working with AWT classes https://www.javatpoint.com/event-h andling-in-java https://www.javatpoint.com/java-a wt
Creating, reading, updating, and deleting data in a database is a common task in many applications, and JDBC (Java Database Connectivity) is a Java API that allows you to connect to a database and perform these operations, the steps of setting up a simple CRUD (create, read, update, delete) operation using JDBC.are… 1. Connect to the database The first step is to establish a connection to the database. You can do this by loading the JDBC driver and creating a connection object. try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "username", "password"); System.out.println("Connection established."); } catch (Exception e) { e.printStackTrace(); }
2. Create a new record Once you have a connection to the database, you can use the connection object to create a new record in the database. To do this, you will need to use an SQL INSERT statement and execute it using the connection object. try { String sql = "INSERT INTO mytb VALUES (333,’Girish’)"; Statement statement = con.createStatement(); statement.executeUpdate(sql); System.out.println("Record created."); } catch (SQLException e) { e.printStackTrace(); }
3. Read a record To read a record from the database, you will need to use an SQL SELECT statement and execute it using the connection object. The result of the query will be a ResultSet object that you can use to access the data in the record. try { String sql = "SELECT * FROM mytb"; Statement statement = con.createStatement(); ResultSet result = statement.executeQuery(sql); if (result.next()) { int id= result.getInt(“id"); String name = result.getString(“name"); System.out.println(“Id: " + id); System.out.println(“Name: " + name); } } catch (SQLException e) { e.printStackTrace(); }
4. Update a record To update a record in the database, you will need to use an SQL UPDATE statement and execute it using the connection object. try { String sql = "UPDATE mytb SET name =‘T.Lavanya’ WHERE id = 111"; Statement statement = con.createStatement(); statement.executeUpdate(sql); System.out.println("Record updated."); } catch (SQLException e) { e.printStackTrace(); }
5. Delete a record To delete a record from the database, you will need to use an SQL DELETE statement and execute it using the connection object. try { String sql = "DELETE FROM table_name WHERE id = 333"; Statement statement = con.createeStatement(); statement.executeUpdate(sql); System.out.println("Record deleted."); } catch (SQLException e) { e.printStackTrace(); } CRUD operations in Java can be easily performed using JDBC. With a few simple steps, you can connect to a database, create new records, read existing records, update records, and delete records. This allows you to easily manage your data and maintain the integrity of your application.
Create and Read Operation: import jdbc.sql.*; public class Main { public static void main(String[] args) { // Database URL, username, and password String url = "jdbc:mysql://localhost:3306/db"; String user = "root"; // Replace with your MySQL username String password = ""; // Replace with your MySQL password // SQL query to be executed String query = "Insert into mytb values(333,'Girish')"; String squery ="select * from mytb"; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { // Establishing the connection connection = DriverManager.getConnection(url, user, password); // Creating a Statement object statement = connection.createStatement(); // Executing the query statement.executeUpdate(query); resultSet = statement.executeQuery(squery // Processing the result while (resultSet.next()) { // Assuming your table has a column named 'id' and 'name' int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } } catch (SQLException e) { e.printStackTrace(); } finally { // Closing the resources resultSet.close(); statement.close(); connection.close(); } } } OUTPUT: ID: 111, Name: Lavanya ID: 222, Name: Suja ID: 333, Name: Girish
Event Handling Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.
Two Event Handling Mechanisms Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model. The Delegation Event Model has the following key participants namely: Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object. Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event and then returns.
The Delegation Event Model Steps involved in event handling The User clicks the button and the event is generated. Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object. Event object is forwarded to the method of registered listener class. the method is now get executed and returns.
Event Listener Interfaces Points to remember about listener In order to design a listener class we have to develop some listener interfaces.These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class. If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.
Java event handling by implementing ActionListener import java.awt.*; import java.awt.event.*; class AEvent extends Frame implements ActionListener{ TextField tf; AEvent(){ //create components tf=new TextField(); tf.setBounds(60,50,170,20); Button b=new Button("click me"); b.setBounds(100,120,80,30); //register listener b.addActionListener(this);//passing current instance //add components and set size, layout and visibility add(b);add(tf); setSize(300,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e){ tf.setText("Welcome"); } public static void main(String args[]){ new AEvent(); } }
Working with AWT Classes: Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java. Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS). The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. Why AWT is platform dependent? Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like TextField, ChechBox, button, etc. For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their native components and AWT directly calls the native subroutine that creates those components. In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy The hierarchy of Java AWT classes are given below.
Components All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for each component as shown in above diagram. In order to place every component in a particular position on a screen, we need to add them to a container. Container The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel. It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls the layout of components. Types of containers: There are four types of containers in Java AWT: Window Panel Frame Dialog
Window The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. We need to create an instance of Window class to create this container. Panel The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the components. It can have other components like button, text field etc. An instance of Panel class creates a container, in which we can add components. Frame The Frame is the container that contain title bar and border and can have menu bars. It can have other components like button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application. Dialog The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Window class.Unlike Frame, it doesn't have maximize and minimize buttons.
Useful Methods of Component Class
Java AWT Example To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. 1. By extending Frame class (inheritance) 2. By creating the object of Frame class (association) AWT Example by Inheritance Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame. AWTExample1.java’s Output
AWTExample1.java’s Code / importing Java AWT class import java.awt.*; // extending Frame class to our class AWTExample1 public class AWTExample1 extends Frame { // initializing using constructor AWTExample1() { // creating a button Button b = new Button("Click Me!!"); // setting button position on screen b.setBounds(30,100,80,30); // adding button into frame add(b); // frame size 300 width and 300 height setSize(300,300); // setting the title of Frame setTitle("This is our basic AWT example"); // no layout manager setLayout(null); // now frame will be visible, by default it is not visible setVisible(true); } // main method public static void main(String args[]) { // creating instance of Frame class AWTExample1 f = new AWTExample1(); } }
2. AWT Example by Association Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are creating a TextField, Label and Button component on the Frame. AWTExample2.java’s output
AWTExample2.java’s code // importing Java AWT class import java.awt.*; // class AWTExample2 directly creates instance of Frame class class AWTExample2 { // initializing using constructor AWTExample2() { // creating a Frame Frame f = new Frame(); // creating a Label Label l = new Label("Employee id:"); // creating a Button Button b = new Button("Submit"); // creating a TextField TextField t = new TextField(); // setting position of above components in the frame l.setBounds(20, 80, 80, 30); t.setBounds(20, 100, 80, 30); b.setBounds(100, 100, 80, 30); // adding components into frame f.add(b); f.add(l); f.add(t); // frame size 300 width and 300 height f.setSize(400,300); // setting the title of frame f.setTitle("Employee info"); // no layout f.setLayout(null); // setting visibility of frame f.setVisible(true); } // main method public static void main(String args[]) { // creating instance of Frame class AWTExample2 awt_obj = new AWTExample2(); } }

Unit 5 Notes For Java Programming for BCA Madras Univ

  • 1.
    UNIT-5 JDBC CRUD operationsusing Java Event handling: Two event handling mechanisms; delegation event model; event classes; source of events; event listener interface Working with AWT classes https://www.javatpoint.com/event-h andling-in-java https://www.javatpoint.com/java-a wt
  • 2.
    Creating, reading, updating,and deleting data in a database is a common task in many applications, and JDBC (Java Database Connectivity) is a Java API that allows you to connect to a database and perform these operations, the steps of setting up a simple CRUD (create, read, update, delete) operation using JDBC.are… 1. Connect to the database The first step is to establish a connection to the database. You can do this by loading the JDBC driver and creating a connection object. try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "username", "password"); System.out.println("Connection established."); } catch (Exception e) { e.printStackTrace(); }
  • 3.
    2. Create anew record Once you have a connection to the database, you can use the connection object to create a new record in the database. To do this, you will need to use an SQL INSERT statement and execute it using the connection object. try { String sql = "INSERT INTO mytb VALUES (333,’Girish’)"; Statement statement = con.createStatement(); statement.executeUpdate(sql); System.out.println("Record created."); } catch (SQLException e) { e.printStackTrace(); }
  • 4.
    3. Read arecord To read a record from the database, you will need to use an SQL SELECT statement and execute it using the connection object. The result of the query will be a ResultSet object that you can use to access the data in the record. try { String sql = "SELECT * FROM mytb"; Statement statement = con.createStatement(); ResultSet result = statement.executeQuery(sql); if (result.next()) { int id= result.getInt(“id"); String name = result.getString(“name"); System.out.println(“Id: " + id); System.out.println(“Name: " + name); } } catch (SQLException e) { e.printStackTrace(); }
  • 5.
    4. Update arecord To update a record in the database, you will need to use an SQL UPDATE statement and execute it using the connection object. try { String sql = "UPDATE mytb SET name =‘T.Lavanya’ WHERE id = 111"; Statement statement = con.createStatement(); statement.executeUpdate(sql); System.out.println("Record updated."); } catch (SQLException e) { e.printStackTrace(); }
  • 6.
    5. Delete arecord To delete a record from the database, you will need to use an SQL DELETE statement and execute it using the connection object. try { String sql = "DELETE FROM table_name WHERE id = 333"; Statement statement = con.createeStatement(); statement.executeUpdate(sql); System.out.println("Record deleted."); } catch (SQLException e) { e.printStackTrace(); } CRUD operations in Java can be easily performed using JDBC. With a few simple steps, you can connect to a database, create new records, read existing records, update records, and delete records. This allows you to easily manage your data and maintain the integrity of your application.
  • 7.
    Create and ReadOperation: import jdbc.sql.*; public class Main { public static void main(String[] args) { // Database URL, username, and password String url = "jdbc:mysql://localhost:3306/db"; String user = "root"; // Replace with your MySQL username String password = ""; // Replace with your MySQL password // SQL query to be executed String query = "Insert into mytb values(333,'Girish')"; String squery ="select * from mytb"; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { // Establishing the connection connection = DriverManager.getConnection(url, user, password); // Creating a Statement object statement = connection.createStatement(); // Executing the query statement.executeUpdate(query); resultSet = statement.executeQuery(squery // Processing the result while (resultSet.next()) { // Assuming your table has a column named 'id' and 'name' int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } } catch (SQLException e) { e.printStackTrace(); } finally { // Closing the resources resultSet.close(); statement.close(); connection.close(); } } } OUTPUT: ID: 111, Name: Lavanya ID: 222, Name: Suja ID: 333, Name: Girish
  • 9.
    Event Handling Changing thestate of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.
  • 10.
    Two Event HandlingMechanisms Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model. The Delegation Event Model has the following key participants namely: Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object. Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event and then returns.
  • 11.
    The Delegation EventModel Steps involved in event handling The User clicks the button and the event is generated. Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object. Event object is forwarded to the method of registered listener class. the method is now get executed and returns.
  • 12.
    Event Listener Interfaces Pointsto remember about listener In order to design a listener class we have to develop some listener interfaces.These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class. If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.
  • 13.
    Java event handlingby implementing ActionListener import java.awt.*; import java.awt.event.*; class AEvent extends Frame implements ActionListener{ TextField tf; AEvent(){ //create components tf=new TextField(); tf.setBounds(60,50,170,20); Button b=new Button("click me"); b.setBounds(100,120,80,30); //register listener b.addActionListener(this);//passing current instance //add components and set size, layout and visibility add(b);add(tf); setSize(300,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e){ tf.setText("Welcome"); } public static void main(String args[]){ new AEvent(); } }
  • 15.
    Working with AWT Classes: JavaAWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java. Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS). The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. Why AWT is platform dependent? Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like TextField, ChechBox, button, etc. For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their native components and AWT directly calls the native subroutine that creates those components. In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac application in the MAC OS.
  • 16.
    Java AWT Hierarchy Thehierarchy of Java AWT classes are given below.
  • 17.
    Components All the elementslike the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for each component as shown in above diagram. In order to place every component in a particular position on a screen, we need to add them to a container. Container The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel. It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls the layout of components. Types of containers: There are four types of containers in Java AWT: Window Panel Frame Dialog
  • 18.
    Window The window isthe container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. We need to create an instance of Window class to create this container. Panel The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the components. It can have other components like button, text field etc. An instance of Panel class creates a container, in which we can add components. Frame The Frame is the container that contain title bar and border and can have menu bars. It can have other components like button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application. Dialog The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Window class.Unlike Frame, it doesn't have maximize and minimize buttons.
  • 19.
    Useful Methods ofComponent Class
  • 20.
    Java AWT Example Tocreate simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. 1. By extending Frame class (inheritance) 2. By creating the object of Frame class (association) AWT Example by Inheritance Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame. AWTExample1.java’s Output
  • 21.
    AWTExample1.java’s Code / importingJava AWT class import java.awt.*; // extending Frame class to our class AWTExample1 public class AWTExample1 extends Frame { // initializing using constructor AWTExample1() { // creating a button Button b = new Button("Click Me!!"); // setting button position on screen b.setBounds(30,100,80,30); // adding button into frame add(b); // frame size 300 width and 300 height setSize(300,300); // setting the title of Frame setTitle("This is our basic AWT example"); // no layout manager setLayout(null); // now frame will be visible, by default it is not visible setVisible(true); } // main method public static void main(String args[]) { // creating instance of Frame class AWTExample1 f = new AWTExample1(); } }
  • 22.
    2. AWT Exampleby Association Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are creating a TextField, Label and Button component on the Frame. AWTExample2.java’s output
  • 23.
    AWTExample2.java’s code // importingJava AWT class import java.awt.*; // class AWTExample2 directly creates instance of Frame class class AWTExample2 { // initializing using constructor AWTExample2() { // creating a Frame Frame f = new Frame(); // creating a Label Label l = new Label("Employee id:"); // creating a Button Button b = new Button("Submit"); // creating a TextField TextField t = new TextField(); // setting position of above components in the frame l.setBounds(20, 80, 80, 30); t.setBounds(20, 100, 80, 30); b.setBounds(100, 100, 80, 30); // adding components into frame f.add(b); f.add(l); f.add(t); // frame size 300 width and 300 height f.setSize(400,300); // setting the title of frame f.setTitle("Employee info"); // no layout f.setLayout(null); // setting visibility of frame f.setVisible(true); } // main method public static void main(String args[]) { // creating instance of Frame class AWTExample2 awt_obj = new AWTExample2(); } }