***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***

posts

    Types of event classes in Java

    An event is one of the most important concepts in Java. The change in the state of an object or behavior by performing actions is referred to as an Event in Java. Actions include button click, keypress, page scrolling, or cursor movement.

    Some of the most used Event classes are:

    Event Class

    Listener Interface

    Methods

    Descriptions

    1.

    ActionEvent

    ActionListener

    actionPerformed()

    ActionEvent indicates that a component-defined action occurred.

    2.

    AdjustmentEvent

    AdjustmentListener

    adjustmentValueChanged()

    Adjustment events occur by an adjustable object like a scrollbar.

    3.

    ComponentEvent

    ComponentListener

    componentResized(), componentMoved(), componentShown() and

     componentHidden()

    An event occurs when a component moved, changed its visibility or the size changed.

    4.

    ContainerEvent

    ContainerListener

    componentRemoved() and

    componentAdded()

    The event is fired when a component is added or removed from a container.

    5.

    FocusEvent

    FocusListener

    focusLost() and

     focusGained()

    Focus events include focus, focusout, focusin, and blur.

    6.

    ItemEvent

    ItemListener

    itemStateChanged()

    Item event occurs when an item is selected.

    7.

    KeyEvent

    KeyListener

    keyPressed(), keyReleased(), and keyTyped().

    A key event occurs when the user presses a key on the keyboard.

    8.

    MouseEvent

    MouseListener and MouseMotionListener

    mouseClicked(), mousePressed(), mouseEntered(), mouseExited() and

     mouseReleased() are the

     mouseListener methods.

     mouseDregged() and

     mouseMoved() are the

     MouseMotionListener()

     methods.

    A mouse event occurs when the user interacts with the mouse.

    9.

    MouseWheelEvent

    MouseWheelListener

    mouseWheelMoved().

    MouseWheelEvent occurs when the mouse wheel rotates in a component.

    10.

    TextEvent

    TextListener

    textChanged()

    TextEvent occurs when an object's text change.

    11.

    WindowEvent

    WindowListener

    windowActivated(), windowDeactivated(), windowOpened(), windowClosed(), windowClosing(), windowIconfied() and

     windowDeiconified().

    Window events occur when a window's status is changed.


    JDBC - Statements, PreparedStatement and CallableStatement

    The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database.

    I. Statement - The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

    Commonly used methods of Statement interface:

    1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.

    2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.

    3) public boolean execute(String sql): is used to execute queries that may return multiple results.

    4) public int[] executeBatch(): is used to execute batch of commands.

     

    II. PreparedStatement - The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query. The PreparedStatement interface accepts input parameters at runtime.

    The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.

    PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");  


    III. CallableStatement - CallableStatement interface is used to call the stored procedures and functions. Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure.

    CallableStatement cstmt = null;

    String SQL = "{call getEmpName (?, ?)}";

                 cstmt = conn.prepareCall (SQL);

     

    Ex: JDBC Example

    import java.sql.*;

    public class FirstExample {

       static final String DB_URL = "jdbc:mysql://localhost/STUDENT";

       static final String USER = "guest";

       static final String PASS = "guest123";

       static final String QUERY = "SELECT id, first, last, age FROM Employees";

       public static void main(String[] args) {

          // Open a connection

          try{

            Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

             Statement stmt = conn.createStatement();

             ResultSet rs = stmt.executeQuery(QUERY);) {

             // Extract data from result set

             while (rs.next()) {

                // Retrieve by column name

                System.out.print("ID: " + rs.getInt("id"));

                System.out.print(", Age: " + rs.getInt("age"));

                System.out.print(", First: " + rs.getString("first"));

                System.out.println(", Last: " + rs.getString("last"));

             }

          } catch (SQLException e) {

             e.printStackTrace();

          }

       }

    }

    JDBC Driver

    JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server. The Java.sql package that ships with JDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implement the java.sql.Driver interface in their database driver.

    JDBC Drivers Types

    JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4.

    Type 1 − JDBC-ODBC Bridge Driver

    In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database.

    Type 2 − JDBC-Native API

    In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine.

    Type 3 − JDBC-Net pure Java

    In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

    Type 4 − 100% Pure Java

    In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

    NOTE:

    Which Driver to be Used?

    If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.

    If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.

    Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database.

    The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only.

    Creating JDBC Application

    There are following six steps involved in building a JDBC application −

    • Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
    • Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
    • Create Statement
    • Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
    • Extract data from result set − Requires that you use the appropriate  ResultSet.getXXX() 

    method to retrieve the data from the result set.

    • Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

    JDBC - Database Connection 

    The programming involved to establish a JDBC connection simple steps:

    1. Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code.

    To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code −

    import java.sql.* ;  // for standard JDBC programs

    2. Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.

    The most common approach to register a driver is to use Java's Class.forName() method, to dynamically load the driver's class file into memory, which automatically registers it.

    Class.forName("oracle.jdbc.driver.OracleDriver");

    The second approach you can use to register a driver, is to use the static DriverManager.registerDriver() method.

    The registerDriver() method can be used if you are using a non-JDK compliant JVM, such as the one provided by Microsoft.

    Driver myDriver = new oracle.jdbc.driver.OracleDriver();

          DriverManager.registerDriver( myDriver );

    3. Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect.

    After loaded the driver, a connection can be established using the  DriverManager.getConnection() method.

    The three overloaded DriverManager.getConnection() methods −

    • getConnection(String url)
    • getConnection(String url, Properties prop)
    • getConnection(String url, String user, String password)

    Here each form requires a database URL. A database URL is an address that points to your database.

    4. Create Connection Object − Finally, code a call to the DriverManager object's 

    getConnection( ) method to establish actual database connection.

    Connection conn = DriverManager.getConnection(URL, USER, PASS);


         5. Create statement -  

         createStatement() of Connection class is used to make object of Statements.

            Eg: Statement stat=con.createStatement();

      Statement object can call executeQuery(“SQL Command”) to execute a select statement.

      Use executeUpdate(“SQL Command”) to execute any data updation commands

      Three types of statements each reflecting a specific SQL statements

      Statement

      PreparedStatement

      CallableStatement 

        6. ExecuteQuery()    

        An executeQuery() method retrives the selected records as an object of ResultSet class. It stores data     in tabular format. Rowid and ColID can be used to identify each data. Rows are records of table and     columns are fields of table

            A cursor is attached to fetch data from any row . Allows the program to scroll through each row             and read all the columns of the data

        7. Close the statement and connection

        At the end of your JDBC program, it is required explicitly to close all the connections to the database     to end each database session (conn.close()). However, if you forget, Java's garbage collector will             close the connection when it cleans up stale objects.

    Ex: JDBC Example

    import java.sql.*;

    public class FirstExample {

       static final String DB_URL = "jdbc:mysql://localhost/STUDENT";

       static final String USER = "guest";

       static final String PASS = "guest123";

       static final String QUERY = "SELECT id, first, last, age FROM Employees";

       public static void main(String[] args) {

          // Open a connection

          try{

            Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

             Statement stmt = conn.createStatement();

             ResultSet rs = stmt.executeQuery(QUERY);) {

             // Extract data from result set

             while (rs.next()) {

                // Retrieve by column name

                System.out.print("ID: " + rs.getInt("id"));

                System.out.print(", Age: " + rs.getInt("age"));

                System.out.print(", First: " + rs.getString("first"));

                System.out.println(", Last: " + rs.getString("last"));

             }

          } catch (SQLException e) {

             e.printStackTrace();

          }

       }

    }

    JDBC and JDBC Architecture

    JDBC or Java Database Connectivity is a specification from Sun microsystems that provides a standard abstraction (that is API or Protocol) for java applications to communicate with various databases. JDBC along with the database driver is capable of accessing databases and spreadsheets. 

    The classes and interfaces of JDBC allows application to send request made by users to the specified database.

    Interacting with a database requires efficient database connectivity which can be achieved by using the ODBC(Open database connectivity) driver. This driver is used with JDBC to interact or communicate with various kinds of databases such as Oracle, MS Access, Mysql and SQL server database. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.

    The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.

    • Making a connection to a database.
    • Creating SQL or MySQL statements.
    • Executing SQL or MySQL queries in the database.
    • Viewing & Modifying the resulting records.

    JDBC Architecture

    The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers −

    • JDBC API − This provides the application-to-JDBC Manager connection.
    • JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

    The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.

    The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

    Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application −


    Common JDBC Components

    The JDBC API provides the following interfaces and classes −

    • DriverManager − This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
    • Driver − This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.
    • Connection − This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.
    • Statement − You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.
    • ResultSet − These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.
    • SQLException − This class handles any errors that occur in a database application.