SlideShare a Scribd company logo
1 of 45
Creating Applications Using Advanced Features
of JDBC

Pre-assessment Questions
    1.   ______________ layer signifies a Java application that uses the JDBC API to
         interact with the JDBC drivers.
         a.   JDBC application layer
         b.   JDBC driver layer
         c.   JDBC driver manager layer
         d.   JDBC API layer

    2.   A JDBC __________ is a software that a Java application uses to access a
         database.
         a.   Driver manager
         b.   Driver
         c.   DSN
         d.   CLI



 ©NIIT                   JDBC and JavaBeans                Lesson 1B / Slide 1 of 45
Creating Applications Using Advanced Features
of JDBC

Pre-assessment Questions (Contd.)
    1.   Which JDBC driver works as an interface between the JDBC application and
         the ODBC driver ?
         a.   Native-API-Partly-Java driver
         b.   Native Protocol Pure-Java driver
         c.   JDBC-ODBC Bridge driver
         d.   JDBC-Net-Pure-Java driver

    •    Which JDBC driver maps the JDBC calls to the native method calls, which are
         passed to the local native Call Level Interface (CLI)?
         a.  Native-API-Partly-Java driver
         b.  JDBC-ODBC Bridge driver
         c.  Native Protocol Pure-Java driver
         d.  JDBC-Net-Pure-Java driver



 ©NIIT                   JDBC and JavaBeans                Lesson 1B / Slide 2 of 45
Creating Applications Using Advanced Features
of JDBC

Pre-assessment Questions (Contd.)
    1.   Which interface enables you to establish a connection between a Java
         application and a database ?
         •    Statement interface
         •    ResultSet interface
         •    DriverManager interface
         •    Connection interface




 ©NIIT                   JDBC and JavaBeans                Lesson 1B / Slide 3 of 45
Creating Applications Using Advanced Features
of JDBC

Solutions to Pre-assessment
  Questions
    •    a. Java application layer
    •    b. Driver
    •    c. JDBC-ODBC Bridge driver
    •    a. Native-API-Partly-Java driver
    •    d. Connection interface




 ©NIIT                   JDBC and JavaBeans   Lesson 1B / Slide 4 of 45
Creating Applications Using Advanced Features
of JDBC

Objectives
    In this section, you will learn about:


         •   Creating applications using the PreparedStatement object
         •   Managing database transactions
         •   Performing batch updates
         •   Creating and calling stored procedures in JDBC
         •   Using metadata in JDBC




 ©NIIT                     JDBC and JavaBeans               Lesson 1B / Slide 5 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
the PreparedStatement Object
    •    The PreparedStatement interface is derived from the Statement interface and
         is available in the java.sql package.
    •    The PreparedStatement object:
           • Allows you to pass runtime parameters to the SQL statements to query
              and modify the data in a table.
           • Is compiled and prepared only once by JDBC. The future invocation of the
              PreparedStatement object does not recompile the SQL statements.
           • Helps in reducing the load on the database server and thus improving the
              performance of the application.




 ©NIIT                     JDBC and JavaBeans                Lesson 1B / Slide 6 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
the PreparedStatement Object
(Contd.)
    •    Methods of the PreparedStatement Interface
          • The PreparedStatement interface inherits the following methods to
             execute SQL statements from the Statement interface:
               • ResultSet executeQuery(): Executes a SELECT statements and
                 returns the result in a ResultSet object.
               • int executeUpdate(): Executes an SQL statement, INSERT, UPDATE,
                 or DELETE and returns the count of the rows affected.
               • boolean execute(): Executes an SQL statement and returns a
                 boolean value.




 ©NIIT                   JDBC and JavaBeans              Lesson 1B / Slide 7 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
the PreparedStatement Object
(Contd.)
         •   The prepareStatement() method of the Connection object is used to
             submit parameterized query to a database.
         •   The SQL statement can contain ‘?’ symbol as placeholders that can be
             replaced by input parameters at runtime. For example,
             stat=con.prepareStatement("SELECT * FROM authors WHERE au_id
             = ?");
         •   The value of each ‘?’ parameter is set by calling an appropriate setXXX()
             method, where XXX is the data type of the parameter. For example,
             stat.setString(1,"1001");
             ResultSet result=stat.executeQuery();



 ©NIIT                    JDBC and JavaBeans                 Lesson 1B / Slide 8 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
the PreparedStatement Object
(Contd.)
    •    Retrieving Rows
          • The code snippet to retrieve books written by an author from the
               titles table using the PreparedStatement object is:
               String str = "SELECT * FROM titles WHERE au_id = ?";
               PreparedStatement ps= con.prepareStatement(str);
               ps.setString(1, "1001");
               ResultSet rs=ps.executeQuery();




 ©NIIT                  JDBC and JavaBeans               Lesson 1B / Slide 9 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
the PreparedStatement Object
(Contd.)
    •    Inserting Rows
          • The code snippet to create a PreparedStatement object that inserts a
                row into authors table by passing authors data at runtime is:
                String str = "INSERT INTO authors (au_id, au_fname,
                au_lname) VALUES (?, ?, ?)";
                PreparedStatement ps = con.prepareStatement(str);
                ps.setString(1, "1001");
                ps.setString(2, "Abraham");
                ps.setString(3, "White");
                int rt=ps.executeUpdate();


 ©NIIT                  JDBC and JavaBeans             Lesson 1B / Slide 10 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
  the PreparedStatement Object
  (Contd.)
    •    Updating and Deleting Rows
         • The code snippet to modify the state to CA where city is Oakland in the
             authors table using the PreparedStatement object is:
             String str = "UPDATE authors SET state= ? WHERE city= ? ";
             PreparedStatement ps = con.prepareStatement(str);
             ps.setString(1, "CA");
             ps.setString(2, "Oakland");
             int rt=ps.executeUpdate();




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 11 of 45
Creating Applications Using Advanced Features
of JDBC

Querying and Modifying Data Using
  the PreparedStatement Object
  (Contd.)
    •    The code snippet to delete a row from the authors table where author’s first
         name is Abraham using the PreparedStatement object is:
         String str = "DELETE FROM authors WHERE au_fname= ? ";
         PreparedStatement ps = con.prepareStatement(str);
         ps.setString(1, "Abraham");
         int rt=ps.executeUpdate();




 ©NIIT                   JDBC and JavaBeans                Lesson 1B / Slide 12 of 45
Creating Applications Using Advanced Features
of JDBC

Demonstration- Creating an
  Application that Uses
  PreparedStatement Object
    •    Problem Statement


         •   The management of a departmental store has decided to
             computerize the inventory. You have been asked to create the
             Product Information application that has an interactive user
             interface. The application should allow the user to add, update,
             and delete product information from the product table.




 ©NIIT                 JDBC and JavaBeans             Lesson 1B / Slide 13 of 45
Creating Applications Using Advanced Features
of JDBC

Demonstration- Creating an
  Application that Uses
  PreparedStatement Object (Contd.)
    •    Problem Statement (Contd.)
         • The user interface of the application should be as shown in the
             following figure:




 ©NIIT                 JDBC and JavaBeans            Lesson 1B / Slide 14 of 45
Creating Applications Using Advanced Features
of JDBC

Demonstration- Creating an
  Application that Uses
  PreparedStatement Object (Contd.)
    •    Solution


         •   The GUI for the application is created using the java.swing
             package. The database operations are performed using the
             PreparedStatement object.
         •   To solve the above problem, perform the following tasks:
             •   Code the application.
             •   Compile and execute the application.




 ©NIIT                 JDBC and JavaBeans             Lesson 1B / Slide 15 of 45
Creating Applications Using Advanced Features
of JDBC

Managing Database Transactions
    •    A transaction:
         • Is a set of one or more SQL statements that are executed as a single
              unit.
         • Is complete only when all the SQL statements in a transaction execute
              successfully.
         • Maintains consistency of data in a database.




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 16 of 45
Creating Applications Using Advanced Features
of JDBC

Managing Database Transactions
(Contd.)
    •    JDBC API provides support for transaction management.
    •    The database transactions can be committed in two ways in the JDBC
         applications:
          • Implicit: The Connection object uses the auto-commit mode to
               execute the SQL statements implicitly.
          • Explicit: The auto-commit mode is set to false to commit the
               transaction statement explicitly. The method call to set the auto-
               commit mode to false is:
               con.setAutoCommit(false);




 ©NIIT                   JDBC and JavaBeans                Lesson 1B / Slide 17 of 45
Creating Applications Using Advanced Features
of JDBC

Managing Database Transactions
(Contd.)
    •    Committing a Transaction
          • The commit() method is used to reflect the changes made by the
            transactions in a database.
          • The rollback() method is used to undo the changes made in the
            database after the last commit operation.
          • You need to explicitly invoke commit() and rollback() methods.




 ©NIIT                    JDBC and JavaBeans             Lesson 1B / Slide 18 of 45
Creating Applications Using Advanced Features
of JDBC

Performing Batch Updates
    •    A batch:
         • Is a group of update statements that are sent to a database to be
              executed as a single unit.
         • Reduces network calls between the application and the database.
         • Is a more efficient way as compared to the processing of a single SQL
              statement.




 ©NIIT                  JDBC and JavaBeans               Lesson 1B / Slide 19 of 45
Creating Applications Using Advanced Features
of JDBC

Performing Batch Updates (Contd.)
    •    Implementing Batch Updates in JDBC
         • The Statement or PreparedStatement interface provides the following
             methods to create and execute a batch of SQL statements:
             • void addBatch(): Adds an SQL statement to a batch.
             • int executeBatch(): Sends a batch of SQL statements to a
                 database for processing and returns the total number of the rows
                 updated.
             • void clearBatch(): Removes the SQL statements from the
                 batch.




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 20 of 45
Creating Applications Using Advanced Features
of JDBC

Performing Batch Updates (Contd.)
         •   When a Statement object is created to perform batch updates, an
             empty array is associated with the object.
         •   Multiple SQL statements can be added to the empty array to execute
             them as a batch.
         •   You also need to disable the auto-commit mode using
             setAutoCommit(false) while working with batch updates in JDBC.
         •   The executeBatch() method returns an integer array that stores the
             values of the update count.
         •   The update count is the total number of rows affected when an SQL
             statement in a batch is processed.




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 21 of 45
Creating Applications Using Advanced Features
of JDBC

Performing Batch Updates (Contd.)
         •   The code snippet to create a batch of SQL statements is:
             con.setAutoCommit(false);
             Statement stmt=con.createStatement();
             stmt.addBatch("INSERT INTO product (p_id, p_desc) VALUES
             (1001, 'Printer')");
             stmt.addBatch("INSERT INTO product (p_id, p_desc) VALUES
             (1002, 'Scanner')");


         •   The SQL statements in a batch are processed in the order in which the
             statements appear in a batch.


         •   The method call to execute a batch of SQL statements is:
             int[] updcount=state.executeBatch();



 ©NIIT                  JDBC and JavaBeans               Lesson 1B / Slide 22 of 45
Creating Applications Using Advanced Features
of JDBC

Performing Batch Updates (Contd.)
    •    Exception Handling in Batch Updates
         • The batch update operations can throw two types of exceptions:
             • SQLException
             • BatchUpdateException
         • The BatchUpdateException class is derived from SQLException class.




 ©NIIT                  JDBC and JavaBeans            Lesson 1B / Slide 23 of 45
Creating Applications Using Advanced Features
of JDBC

Performing Batch Updates (Contd.)
         •   The the SQLException is thrown by the JDBC API methods, addBatch()
             or executeBatch(), when problem occurs while accessing a database.
         •   The BatchUpdateException exception is thrown when the SQL
             statements in the batch cannot be executed due to:
             • Presence of illegal arguments in the SQL statement.
             • Absence of the database table from which you need to retrieve
                  data.
         •   The BatchUpdateException uses an array of the update count to
             identify the SQL statement that throws the exception.




 ©NIIT                 JDBC and JavaBeans              Lesson 1B / Slide 24 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC
    •    The java.sql package provides the CallableStatement interface that
         contains various methods to enable you to call the stored procedures from a
         database.
    •    The CallableStatement interface is derived from the PreparedStatement
         interface.




 ©NIIT                   JDBC and JavaBeans               Lesson 1B / Slide 25 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC (Contd.)
    •    Creating Stored Procedure
         • Stored Procedures:
              • Can be created using the CREATE PROCEDURE SQL statement in
                   JDBC applications.
              • Are of two types:
                   • Parameterized
                   • Non-parameterized




 ©NIIT                 JDBC and JavaBeans             Lesson 1B / Slide 26 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC (Contd.)
    •    A parameterized stored procedure can accept one or multiple parameters.
    •    A parameter of a stored procedure can take any of these forms:
         • IN: Refers to the argument that you pass to a stored procedure.
         • OUT: Refers to the return value of a stored procedure.
         • INOUT: Combines the functionality of the IN and OUT parameters. The
              INOUT parameter enables you to pass an argument to a stored
              procedure. The same parameter can also be used to store a return
              value of a stored procedure.




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 27 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC (Contd.)
    •    Calling a Stored Procedure without Parameters
         • The Connection interface provides the prepareCall() method that is
               used to create the CallableStatement object to call a stored
               procedure.
         • The prepareCall() has the following three forms:
               • CallableStatement prepareCall(String str)
               • CallableStatement prepareCall(String str, int
                    resSetType, int resSetConcurrency)
               • CallableStatement prepareCall(String str, int
                    resSetType, int resSetConcurrency, int
                    resSetHoldability)
         • The syntax to call a stored procedure without parameters is:
               { call <procedure_name> };

 ©NIIT                 JDBC and JavaBeans            Lesson 1B / Slide 28 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC (Contd.)
    •    Calling a Stored Procedure with Parameters
         • The SQL escape syntax is a standard way to call a stored procedure
               from a Relational Database Management System (RDBMS) and is
               independent of the RDBMS.
         • There are two forms of the SQL escape syntax, one that contains result
               parameter and one that does not.
         • The syntax of the SQL escape syntax is:
               {[? =] call <procedure_name> [<parameter1>,<parameter2>, ...,
               <parameterN>]}




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 29 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC (Contd.)
         •   The placeholders are used to represent the IN, OUT, and INOUT
             parameters of a stored procedure in the procedure call.
         •   The syntax to call a stored procedure with parameters is:
             { call <procedure_name>(?) };
         •   You need to set the value of the IN parameters using the set methods
             before the CallableStatement object is executed.
         •   The syntax to set the value of the IN parameter is:
             <CallableStatement_object>.setInt(<value>);




 ©NIIT                  JDBC and JavaBeans               Lesson 1B / Slide 30 of 45
Creating Applications Using Advanced Features
of JDBC

Creating and Calling Stored
  Procedures in JDBC (Contd.)
    •    If the stored procedure contains OUT and INOUT parameters, these
         parameters should be registered with the corresponding JDBC types.
    •    The registerOut() method is used to register the parameters.
    •    The prototypes of the registerOut() method are:
         • registerOut(int index, int stype)
         • registerOut(int index, int stype, int scale)




 ©NIIT                   JDBC and JavaBeans              Lesson 1B / Slide 31 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC
    •    Metadata is the information about data, such as structure and properties of
         table.
    •    The metadata of the employee table includes following information:
         • Names of the columns.
         • Data type of each column.
         • Constraints to enter data values in the table columns.
    •    JDBC API provides the following two metadata interfaces to retrieve the
         information about the database and result set:
         • DatabaseMetaData interface
         • ResultSetMetaData interface




 ©NIIT                   JDBC and JavaBeans                Lesson 1B / Slide 32 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
    •    Using DatabaseMetaData Interface
         • The DatabaseMetaData interface provides the methods that enable you
              to determine the properties of a database or RDBMS.
         • An object of DatabaseMetaData is created using the getMetaData()
              method of the Connection interface.
         • The method call to create an object of the DatabaseMetaData interface
              is:
              DatabaseMetaData dm=con.getMetaData();




 ©NIIT                  JDBC and JavaBeans              Lesson 1B / Slide 33 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
    •     The following table lists the commonly used methods of the
          DatabaseMetaData interface:

                  Method                                       Description


ResultSet getColumns(String catalog,             Retrieves the information about a
String schema, String table_name,                column of a database table that is
String column_name)                              available in the specified catalog.

Connection getConnection()                       Retrieves the database connection that
                                                 creates the DatabaseMetaData object.

String getDriverName()                           Retrieves the name of the JDBC driver
                                                 for the DatabaseMetaData object.

String getDriverVersion()                        Retrieves the version of the JDBC driver.


  ©NIIT                     JDBC and JavaBeans                Lesson 1B / Slide 34 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
  •      The methods of the DatabaseMetaData interface: (Contd.)

                   Method                                   Description


 ResultSet getPrimaryKeys(String               Retrieves the information about the
 catalog, String schema, String table)         primary keys of the database tables.

 String getURL()                               Retrieves the URL of the database.


 boolean isReadOnly()                          Returns a boolean value that indicates
                                               whether the database is a read only
                                               database.
 boolean supportsSavepoints()                  Returns a boolean value that indicates
                                               whether the database supports
                                               savepoints.

 ©NIIT                    JDBC and JavaBeans              Lesson 1B / Slide 35 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
  •      Using the ReultSetMetaData Interface
         • The ReultSetMetaData Interface contains various methods that enable
              you to retrieve information about the data in a result set.
         • The ResultSet interface provides the getMetaData() method to create
              an object of the ResultSetMetaData interface.
         • The method call to create an object of the ResultSetMetaData
              interface:
              ResultSetMetaData rm=rs.getMetaData();




 ©NIIT                   JDBC and JavaBeans             Lesson 1B / Slide 36 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
   •     The following table lists the commonly used methods of the
         ResultSetMetaData interface:

           Method                                      Description


int getColumnCount()              Returns an integer indicating the total number of
                                  columns in a ResultSet object.

String getColumnLabel(int         Retrieves the title of the table column corresponding
column_index)                     to the index passed as a parameter to this method.

String getColumnName(int          Retrieves the name of the table column corresponding
column_index)                     to the index passed as a parameter to this method.

int getColumnType(int             Retrieves the SQL data type of the table column
column_index)                     corresponding to the index passed as a parameter.


 ©NIIT                     JDBC and JavaBeans               Lesson 1B / Slide 37 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
   •     The methods of the ResultSetMetaData interface: (Contd.)

           Method                                   Description


String getTableName(int          Retrieves the name of the database table that
column_index)                    contains the column corresponding to the index
                                 passed as a parameter.
boolean                          Returns a boolean value that indicates whether the
isAutoIncrement(int              table column corresponding to the index passed as a
column_index)                    parameter increments automatically.

boolean                          Returns a boolean value that indicates whether the
isCaseSensitive(int              table column corresponding to the index passed as a
column_index)                    parameter is case sensitive.


 ©NIIT                    JDBC and JavaBeans              Lesson 1B / Slide 38 of 45
Creating Applications Using Advanced Features
of JDBC

Using Metadata in JDBC (Contd.)
  •      The methods of the ResultSetMetaData interface: (Contd.)

                 Method                               Description



      boolean isReadOnly(int            Returns a boolean value that indicates
      column_index)                     whether the column in a ResultSet
                                        corresponding to the index passed as a
                                        parameter is read only.

      boolean isWritable(int            Returns a boolean value that indicates
      column_index)                     whether ResultSet column corresponding
                                        to the index passed as a parameter is
                                        updatable.



 ©NIIT                    JDBC and JavaBeans              Lesson 1B / Slide 39 of 45
Creating Applications Using Advanced Features
of JDBC

Demonstration- Creating an
  Application to Retrieve the
  Information of Database Tables
    •    Problem Statement


         •   The Manager of New Publishers publishing company, sometimes
             require the information about the tables of the database used by
             the company. He is not familiar with the SQL statements,
             therefore, he has asked you to create an application to
             determine the total number of columns and the data types of the
             columns of a given table. The table name has to be specified at
             the runtime.




 ©NIIT                 JDBC and JavaBeans            Lesson 1B / Slide 40 of 45
Creating Applications Using Advanced Features
of JDBC

Demonstration- Creating an
  Application to Retrieve the
  Information of Database Tables
  (Contd.)
    •    Solution


         •   The getColumnName(), getColumnCount(), and getColumnTypeName()
             methods of the ResultSetMetaData interface are used to develop
             the above application. To solve the above problem, perform the
             following tasks:
             •    Code the application.
             •    Compile and execute the application.


 ©NIIT                 JDBC and JavaBeans           Lesson 1B / Slide 41 of 45
Creating Applications Using Advanced Features
of JDBC

Summary
    In this lesson, you learned:
    • The PreparedStatement object of the Connection interface allows you to
         pass runtime parameters to the SQL statements using the placeholders.
    • There can be multiple placeholders in a single SQL statement. An index value
         is associated with each placeholder depending upon the position of the
         placeholder in the SQL statement.
    • The placeholder stores the value assigned to it until the value is explicitly
         changed.
    • A transaction is a set of one or more SQL statements that are executed as a
         single unit. A transaction is complete only when all the SQL statements in a
         transaction are successfully executed.
    • If the setAutoCommit() method is set to true the database operations
         performed by the SQL statements are automatically committed in the
         database.



 ©NIIT                   JDBC and JavaBeans               Lesson 1B / Slide 42 of 45
Creating Applications Using Advanced Features
of JDBC

Summary (Contd.)
    •    The commit() method reflects the changes made by the SQL statements
         permanently in the database.
    •    The rollback() method is used to undo the effect of all the SQL operations
         performed after the last commit operation.
    •    A batch is a group of update statements that are sent to a database to be
         executed as a single unit. You send the batch to a database as a single
         request using the same Connection object.
    •    The executeBatch() method returns an integer array that stores the update
         count for all the SQL statements that are executed successfully in a batch.
         The update count is the number of database rows affected by the database
         operation performed by each SQL statement.
    •    Batch update operations can throw two types of exceptions, SQLException
         and BatchUpdateException.
    •    The SQLException is thrown when the database access problem occurs. The
         SQLException is also thrown when a SELECT statement that returns a
         ResultSet object is executed in a batch.

 ©NIIT                   JDBC and JavaBeans               Lesson 1B / Slide 43 of 45
Creating Applications Using Advanced Features
of JDBC

Summary (Contd.)
    •    The BatchUpdateException is thrown when the SQL statement in the batch
         cannot be executed due to the problem in accessing the specified table or
         presence of illegal arguments in the SQL statement.
    •    The CallableStatement interface contains various methods that enable you
         to call the stored procedures from a database.
    •    The parameters of a stored procedure can take any of these three forms:
         • IN: Refers to the argument that you pass to a stored procedure.
         • OUT: Refers to the return value of a stored procedure.
         • INOUT: Enables you pass an argument to a stored procedure. The same
              parameters can also be used to pass a return value of a stored
              procedure.
    •    Metadata is the information about data, such as structure and properties of
         table.
    •    JDBC API provides two metadata interfaces to retrieve the information about
         the database and result set, DatabaseMetaData and ResultSetMetaData.


 ©NIIT                   JDBC and JavaBeans               Lesson 1B / Slide 44 of 45
Creating Applications Using Advanced Features
of JDBC

Summary (Contd.)
    •    The DatabaseMetaData interface declares methods that enable you to
         determine the properties of a database or RDBMS.
    •    The ResultSetMetaData interface declares methods that enable you to
         determine information about data in a result set.
    •    The getMetaData() method of the Connection interface enables you to
         declare the objects of the DatabaseMetaData interface. The methods in the
         DatabaseMetaData interface retrieve information only about the database to
         which a Java application is connected.
    •    The getMetaData() method of the ResultSet interface enables you to create
         the instance of the ResultSetMetaData interface.




 ©NIIT                   JDBC and JavaBeans              Lesson 1B / Slide 45 of 45

More Related Content

What's hot

Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02
Niit Care
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
Niit Care
 
Ado.net session07
Ado.net session07Ado.net session07
Ado.net session07
Niit Care
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
Niit Care
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
Niit Care
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
Ambarish Rai
 

What's hot (20)

Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
 
Ado.net session07
Ado.net session07Ado.net session07
Ado.net session07
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
 
Ado.net
Ado.netAdo.net
Ado.net
 
Jpa
JpaJpa
Jpa
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
Java beans
Java beansJava beans
Java beans
 
Hibernate
HibernateHibernate
Hibernate
 
Introduction to OO, Java and Eclipse/WebSphere
Introduction to OO, Java and Eclipse/WebSphereIntroduction to OO, Java and Eclipse/WebSphere
Introduction to OO, Java and Eclipse/WebSphere
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 Specifications
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
 
Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping Tool
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
 
Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examples
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Image Converter
Image ConverterImage Converter
Image Converter
 
Jdbc
JdbcJdbc
Jdbc
 

Viewers also liked

Presentación1.pptx-
 Presentación1.pptx- Presentación1.pptx-
Presentación1.pptx-
eva94
 

Viewers also liked (14)

Presentación1.pptx-
 Presentación1.pptx- Presentación1.pptx-
Presentación1.pptx-
 
Nómina de inscriptos cursos de verano 2012
Nómina de inscriptos cursos de verano 2012Nómina de inscriptos cursos de verano 2012
Nómina de inscriptos cursos de verano 2012
 
Regiones del noa y cronología
Regiones del noa y cronologíaRegiones del noa y cronología
Regiones del noa y cronología
 
COC - MySQL Performance Tuning
COC - MySQL Performance TuningCOC - MySQL Performance Tuning
COC - MySQL Performance Tuning
 
Civilizaciones Egipto.
Civilizaciones Egipto.Civilizaciones Egipto.
Civilizaciones Egipto.
 
Introduccion al Metabolismo
Introduccion al MetabolismoIntroduccion al Metabolismo
Introduccion al Metabolismo
 
Managing Current Liabilities (Gitman)
Managing Current Liabilities (Gitman)Managing Current Liabilities (Gitman)
Managing Current Liabilities (Gitman)
 
Resumen parcial
Resumen parcialResumen parcial
Resumen parcial
 
Case study marki Krakus z Albumu Superbrands Polska 2016
Case study marki Krakus z Albumu Superbrands Polska 2016 Case study marki Krakus z Albumu Superbrands Polska 2016
Case study marki Krakus z Albumu Superbrands Polska 2016
 
La civilización en Egipto. 1ºESO, Curso 2016
La civilización en Egipto. 1ºESO, Curso 2016La civilización en Egipto. 1ºESO, Curso 2016
La civilización en Egipto. 1ºESO, Curso 2016
 
Tema 2.2º ESO. La península Ibérica durante el reino visigodo.
Tema 2.2º ESO. La península Ibérica durante el reino visigodo.Tema 2.2º ESO. La península Ibérica durante el reino visigodo.
Tema 2.2º ESO. La península Ibérica durante el reino visigodo.
 
Religions of europe maps
Religions of europe mapsReligions of europe maps
Religions of europe maps
 
7.7 kingdoms of europe powerpoint
7.7 kingdoms of europe powerpoint7.7 kingdoms of europe powerpoint
7.7 kingdoms of europe powerpoint
 
Chapter 14, lesson 4 enslaved people in the south
Chapter 14, lesson 4   enslaved people in the southChapter 14, lesson 4   enslaved people in the south
Chapter 14, lesson 4 enslaved people in the south
 

Similar to Dacj 4 1-b

Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
Niit Care
 
Java session16
Java session16Java session16
Java session16
Niit Care
 
Jdbc session02
Jdbc session02Jdbc session02
Jdbc session02
Niit Care
 

Similar to Dacj 4 1-b (20)

Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
jdbc
jdbcjdbc
jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Java session16
Java session16Java session16
Java session16
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc session02
Jdbc session02Jdbc session02
Jdbc session02
 
IRJET- Review on Java Database Connectivity
IRJET- Review on Java Database ConnectivityIRJET- Review on Java Database Connectivity
IRJET- Review on Java Database Connectivity
 
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
 
Airline report
Airline reportAirline report
Airline report
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 

More from Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 a
 
Dacj 1-1 c
Dacj 1-1 cDacj 1-1 c
Dacj 1-1 c
 

Recently uploaded

Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Recently uploaded (20)

Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptxBT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
 

Dacj 4 1-b

  • 1. Creating Applications Using Advanced Features of JDBC Pre-assessment Questions 1. ______________ layer signifies a Java application that uses the JDBC API to interact with the JDBC drivers. a. JDBC application layer b. JDBC driver layer c. JDBC driver manager layer d. JDBC API layer 2. A JDBC __________ is a software that a Java application uses to access a database. a. Driver manager b. Driver c. DSN d. CLI ©NIIT JDBC and JavaBeans Lesson 1B / Slide 1 of 45
  • 2. Creating Applications Using Advanced Features of JDBC Pre-assessment Questions (Contd.) 1. Which JDBC driver works as an interface between the JDBC application and the ODBC driver ? a. Native-API-Partly-Java driver b. Native Protocol Pure-Java driver c. JDBC-ODBC Bridge driver d. JDBC-Net-Pure-Java driver • Which JDBC driver maps the JDBC calls to the native method calls, which are passed to the local native Call Level Interface (CLI)? a. Native-API-Partly-Java driver b. JDBC-ODBC Bridge driver c. Native Protocol Pure-Java driver d. JDBC-Net-Pure-Java driver ©NIIT JDBC and JavaBeans Lesson 1B / Slide 2 of 45
  • 3. Creating Applications Using Advanced Features of JDBC Pre-assessment Questions (Contd.) 1. Which interface enables you to establish a connection between a Java application and a database ? • Statement interface • ResultSet interface • DriverManager interface • Connection interface ©NIIT JDBC and JavaBeans Lesson 1B / Slide 3 of 45
  • 4. Creating Applications Using Advanced Features of JDBC Solutions to Pre-assessment Questions • a. Java application layer • b. Driver • c. JDBC-ODBC Bridge driver • a. Native-API-Partly-Java driver • d. Connection interface ©NIIT JDBC and JavaBeans Lesson 1B / Slide 4 of 45
  • 5. Creating Applications Using Advanced Features of JDBC Objectives In this section, you will learn about: • Creating applications using the PreparedStatement object • Managing database transactions • Performing batch updates • Creating and calling stored procedures in JDBC • Using metadata in JDBC ©NIIT JDBC and JavaBeans Lesson 1B / Slide 5 of 45
  • 6. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object • The PreparedStatement interface is derived from the Statement interface and is available in the java.sql package. • The PreparedStatement object: • Allows you to pass runtime parameters to the SQL statements to query and modify the data in a table. • Is compiled and prepared only once by JDBC. The future invocation of the PreparedStatement object does not recompile the SQL statements. • Helps in reducing the load on the database server and thus improving the performance of the application. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 6 of 45
  • 7. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object (Contd.) • Methods of the PreparedStatement Interface • The PreparedStatement interface inherits the following methods to execute SQL statements from the Statement interface: • ResultSet executeQuery(): Executes a SELECT statements and returns the result in a ResultSet object. • int executeUpdate(): Executes an SQL statement, INSERT, UPDATE, or DELETE and returns the count of the rows affected. • boolean execute(): Executes an SQL statement and returns a boolean value. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 7 of 45
  • 8. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object (Contd.) • The prepareStatement() method of the Connection object is used to submit parameterized query to a database. • The SQL statement can contain ‘?’ symbol as placeholders that can be replaced by input parameters at runtime. For example, stat=con.prepareStatement("SELECT * FROM authors WHERE au_id = ?"); • The value of each ‘?’ parameter is set by calling an appropriate setXXX() method, where XXX is the data type of the parameter. For example, stat.setString(1,"1001"); ResultSet result=stat.executeQuery(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 8 of 45
  • 9. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object (Contd.) • Retrieving Rows • The code snippet to retrieve books written by an author from the titles table using the PreparedStatement object is: String str = "SELECT * FROM titles WHERE au_id = ?"; PreparedStatement ps= con.prepareStatement(str); ps.setString(1, "1001"); ResultSet rs=ps.executeQuery(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 9 of 45
  • 10. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object (Contd.) • Inserting Rows • The code snippet to create a PreparedStatement object that inserts a row into authors table by passing authors data at runtime is: String str = "INSERT INTO authors (au_id, au_fname, au_lname) VALUES (?, ?, ?)"; PreparedStatement ps = con.prepareStatement(str); ps.setString(1, "1001"); ps.setString(2, "Abraham"); ps.setString(3, "White"); int rt=ps.executeUpdate(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 10 of 45
  • 11. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object (Contd.) • Updating and Deleting Rows • The code snippet to modify the state to CA where city is Oakland in the authors table using the PreparedStatement object is: String str = "UPDATE authors SET state= ? WHERE city= ? "; PreparedStatement ps = con.prepareStatement(str); ps.setString(1, "CA"); ps.setString(2, "Oakland"); int rt=ps.executeUpdate(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 11 of 45
  • 12. Creating Applications Using Advanced Features of JDBC Querying and Modifying Data Using the PreparedStatement Object (Contd.) • The code snippet to delete a row from the authors table where author’s first name is Abraham using the PreparedStatement object is: String str = "DELETE FROM authors WHERE au_fname= ? "; PreparedStatement ps = con.prepareStatement(str); ps.setString(1, "Abraham"); int rt=ps.executeUpdate(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 12 of 45
  • 13. Creating Applications Using Advanced Features of JDBC Demonstration- Creating an Application that Uses PreparedStatement Object • Problem Statement • The management of a departmental store has decided to computerize the inventory. You have been asked to create the Product Information application that has an interactive user interface. The application should allow the user to add, update, and delete product information from the product table. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 13 of 45
  • 14. Creating Applications Using Advanced Features of JDBC Demonstration- Creating an Application that Uses PreparedStatement Object (Contd.) • Problem Statement (Contd.) • The user interface of the application should be as shown in the following figure: ©NIIT JDBC and JavaBeans Lesson 1B / Slide 14 of 45
  • 15. Creating Applications Using Advanced Features of JDBC Demonstration- Creating an Application that Uses PreparedStatement Object (Contd.) • Solution • The GUI for the application is created using the java.swing package. The database operations are performed using the PreparedStatement object. • To solve the above problem, perform the following tasks: • Code the application. • Compile and execute the application. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 15 of 45
  • 16. Creating Applications Using Advanced Features of JDBC Managing Database Transactions • A transaction: • Is a set of one or more SQL statements that are executed as a single unit. • Is complete only when all the SQL statements in a transaction execute successfully. • Maintains consistency of data in a database. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 16 of 45
  • 17. Creating Applications Using Advanced Features of JDBC Managing Database Transactions (Contd.) • JDBC API provides support for transaction management. • The database transactions can be committed in two ways in the JDBC applications: • Implicit: The Connection object uses the auto-commit mode to execute the SQL statements implicitly. • Explicit: The auto-commit mode is set to false to commit the transaction statement explicitly. The method call to set the auto- commit mode to false is: con.setAutoCommit(false); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 17 of 45
  • 18. Creating Applications Using Advanced Features of JDBC Managing Database Transactions (Contd.) • Committing a Transaction • The commit() method is used to reflect the changes made by the transactions in a database. • The rollback() method is used to undo the changes made in the database after the last commit operation. • You need to explicitly invoke commit() and rollback() methods. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 18 of 45
  • 19. Creating Applications Using Advanced Features of JDBC Performing Batch Updates • A batch: • Is a group of update statements that are sent to a database to be executed as a single unit. • Reduces network calls between the application and the database. • Is a more efficient way as compared to the processing of a single SQL statement. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 19 of 45
  • 20. Creating Applications Using Advanced Features of JDBC Performing Batch Updates (Contd.) • Implementing Batch Updates in JDBC • The Statement or PreparedStatement interface provides the following methods to create and execute a batch of SQL statements: • void addBatch(): Adds an SQL statement to a batch. • int executeBatch(): Sends a batch of SQL statements to a database for processing and returns the total number of the rows updated. • void clearBatch(): Removes the SQL statements from the batch. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 20 of 45
  • 21. Creating Applications Using Advanced Features of JDBC Performing Batch Updates (Contd.) • When a Statement object is created to perform batch updates, an empty array is associated with the object. • Multiple SQL statements can be added to the empty array to execute them as a batch. • You also need to disable the auto-commit mode using setAutoCommit(false) while working with batch updates in JDBC. • The executeBatch() method returns an integer array that stores the values of the update count. • The update count is the total number of rows affected when an SQL statement in a batch is processed. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 21 of 45
  • 22. Creating Applications Using Advanced Features of JDBC Performing Batch Updates (Contd.) • The code snippet to create a batch of SQL statements is: con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.addBatch("INSERT INTO product (p_id, p_desc) VALUES (1001, 'Printer')"); stmt.addBatch("INSERT INTO product (p_id, p_desc) VALUES (1002, 'Scanner')"); • The SQL statements in a batch are processed in the order in which the statements appear in a batch. • The method call to execute a batch of SQL statements is: int[] updcount=state.executeBatch(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 22 of 45
  • 23. Creating Applications Using Advanced Features of JDBC Performing Batch Updates (Contd.) • Exception Handling in Batch Updates • The batch update operations can throw two types of exceptions: • SQLException • BatchUpdateException • The BatchUpdateException class is derived from SQLException class. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 23 of 45
  • 24. Creating Applications Using Advanced Features of JDBC Performing Batch Updates (Contd.) • The the SQLException is thrown by the JDBC API methods, addBatch() or executeBatch(), when problem occurs while accessing a database. • The BatchUpdateException exception is thrown when the SQL statements in the batch cannot be executed due to: • Presence of illegal arguments in the SQL statement. • Absence of the database table from which you need to retrieve data. • The BatchUpdateException uses an array of the update count to identify the SQL statement that throws the exception. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 24 of 45
  • 25. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC • The java.sql package provides the CallableStatement interface that contains various methods to enable you to call the stored procedures from a database. • The CallableStatement interface is derived from the PreparedStatement interface. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 25 of 45
  • 26. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC (Contd.) • Creating Stored Procedure • Stored Procedures: • Can be created using the CREATE PROCEDURE SQL statement in JDBC applications. • Are of two types: • Parameterized • Non-parameterized ©NIIT JDBC and JavaBeans Lesson 1B / Slide 26 of 45
  • 27. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC (Contd.) • A parameterized stored procedure can accept one or multiple parameters. • A parameter of a stored procedure can take any of these forms: • IN: Refers to the argument that you pass to a stored procedure. • OUT: Refers to the return value of a stored procedure. • INOUT: Combines the functionality of the IN and OUT parameters. The INOUT parameter enables you to pass an argument to a stored procedure. The same parameter can also be used to store a return value of a stored procedure. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 27 of 45
  • 28. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC (Contd.) • Calling a Stored Procedure without Parameters • The Connection interface provides the prepareCall() method that is used to create the CallableStatement object to call a stored procedure. • The prepareCall() has the following three forms: • CallableStatement prepareCall(String str) • CallableStatement prepareCall(String str, int resSetType, int resSetConcurrency) • CallableStatement prepareCall(String str, int resSetType, int resSetConcurrency, int resSetHoldability) • The syntax to call a stored procedure without parameters is: { call <procedure_name> }; ©NIIT JDBC and JavaBeans Lesson 1B / Slide 28 of 45
  • 29. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC (Contd.) • Calling a Stored Procedure with Parameters • The SQL escape syntax is a standard way to call a stored procedure from a Relational Database Management System (RDBMS) and is independent of the RDBMS. • There are two forms of the SQL escape syntax, one that contains result parameter and one that does not. • The syntax of the SQL escape syntax is: {[? =] call <procedure_name> [<parameter1>,<parameter2>, ..., <parameterN>]} ©NIIT JDBC and JavaBeans Lesson 1B / Slide 29 of 45
  • 30. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC (Contd.) • The placeholders are used to represent the IN, OUT, and INOUT parameters of a stored procedure in the procedure call. • The syntax to call a stored procedure with parameters is: { call <procedure_name>(?) }; • You need to set the value of the IN parameters using the set methods before the CallableStatement object is executed. • The syntax to set the value of the IN parameter is: <CallableStatement_object>.setInt(<value>); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 30 of 45
  • 31. Creating Applications Using Advanced Features of JDBC Creating and Calling Stored Procedures in JDBC (Contd.) • If the stored procedure contains OUT and INOUT parameters, these parameters should be registered with the corresponding JDBC types. • The registerOut() method is used to register the parameters. • The prototypes of the registerOut() method are: • registerOut(int index, int stype) • registerOut(int index, int stype, int scale) ©NIIT JDBC and JavaBeans Lesson 1B / Slide 31 of 45
  • 32. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC • Metadata is the information about data, such as structure and properties of table. • The metadata of the employee table includes following information: • Names of the columns. • Data type of each column. • Constraints to enter data values in the table columns. • JDBC API provides the following two metadata interfaces to retrieve the information about the database and result set: • DatabaseMetaData interface • ResultSetMetaData interface ©NIIT JDBC and JavaBeans Lesson 1B / Slide 32 of 45
  • 33. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • Using DatabaseMetaData Interface • The DatabaseMetaData interface provides the methods that enable you to determine the properties of a database or RDBMS. • An object of DatabaseMetaData is created using the getMetaData() method of the Connection interface. • The method call to create an object of the DatabaseMetaData interface is: DatabaseMetaData dm=con.getMetaData(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 33 of 45
  • 34. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • The following table lists the commonly used methods of the DatabaseMetaData interface: Method Description ResultSet getColumns(String catalog, Retrieves the information about a String schema, String table_name, column of a database table that is String column_name) available in the specified catalog. Connection getConnection() Retrieves the database connection that creates the DatabaseMetaData object. String getDriverName() Retrieves the name of the JDBC driver for the DatabaseMetaData object. String getDriverVersion() Retrieves the version of the JDBC driver. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 34 of 45
  • 35. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • The methods of the DatabaseMetaData interface: (Contd.) Method Description ResultSet getPrimaryKeys(String Retrieves the information about the catalog, String schema, String table) primary keys of the database tables. String getURL() Retrieves the URL of the database. boolean isReadOnly() Returns a boolean value that indicates whether the database is a read only database. boolean supportsSavepoints() Returns a boolean value that indicates whether the database supports savepoints. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 35 of 45
  • 36. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • Using the ReultSetMetaData Interface • The ReultSetMetaData Interface contains various methods that enable you to retrieve information about the data in a result set. • The ResultSet interface provides the getMetaData() method to create an object of the ResultSetMetaData interface. • The method call to create an object of the ResultSetMetaData interface: ResultSetMetaData rm=rs.getMetaData(); ©NIIT JDBC and JavaBeans Lesson 1B / Slide 36 of 45
  • 37. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • The following table lists the commonly used methods of the ResultSetMetaData interface: Method Description int getColumnCount() Returns an integer indicating the total number of columns in a ResultSet object. String getColumnLabel(int Retrieves the title of the table column corresponding column_index) to the index passed as a parameter to this method. String getColumnName(int Retrieves the name of the table column corresponding column_index) to the index passed as a parameter to this method. int getColumnType(int Retrieves the SQL data type of the table column column_index) corresponding to the index passed as a parameter. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 37 of 45
  • 38. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • The methods of the ResultSetMetaData interface: (Contd.) Method Description String getTableName(int Retrieves the name of the database table that column_index) contains the column corresponding to the index passed as a parameter. boolean Returns a boolean value that indicates whether the isAutoIncrement(int table column corresponding to the index passed as a column_index) parameter increments automatically. boolean Returns a boolean value that indicates whether the isCaseSensitive(int table column corresponding to the index passed as a column_index) parameter is case sensitive. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 38 of 45
  • 39. Creating Applications Using Advanced Features of JDBC Using Metadata in JDBC (Contd.) • The methods of the ResultSetMetaData interface: (Contd.) Method Description boolean isReadOnly(int Returns a boolean value that indicates column_index) whether the column in a ResultSet corresponding to the index passed as a parameter is read only. boolean isWritable(int Returns a boolean value that indicates column_index) whether ResultSet column corresponding to the index passed as a parameter is updatable. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 39 of 45
  • 40. Creating Applications Using Advanced Features of JDBC Demonstration- Creating an Application to Retrieve the Information of Database Tables • Problem Statement • The Manager of New Publishers publishing company, sometimes require the information about the tables of the database used by the company. He is not familiar with the SQL statements, therefore, he has asked you to create an application to determine the total number of columns and the data types of the columns of a given table. The table name has to be specified at the runtime. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 40 of 45
  • 41. Creating Applications Using Advanced Features of JDBC Demonstration- Creating an Application to Retrieve the Information of Database Tables (Contd.) • Solution • The getColumnName(), getColumnCount(), and getColumnTypeName() methods of the ResultSetMetaData interface are used to develop the above application. To solve the above problem, perform the following tasks: • Code the application. • Compile and execute the application. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 41 of 45
  • 42. Creating Applications Using Advanced Features of JDBC Summary In this lesson, you learned: • The PreparedStatement object of the Connection interface allows you to pass runtime parameters to the SQL statements using the placeholders. • There can be multiple placeholders in a single SQL statement. An index value is associated with each placeholder depending upon the position of the placeholder in the SQL statement. • The placeholder stores the value assigned to it until the value is explicitly changed. • A transaction is a set of one or more SQL statements that are executed as a single unit. A transaction is complete only when all the SQL statements in a transaction are successfully executed. • If the setAutoCommit() method is set to true the database operations performed by the SQL statements are automatically committed in the database. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 42 of 45
  • 43. Creating Applications Using Advanced Features of JDBC Summary (Contd.) • The commit() method reflects the changes made by the SQL statements permanently in the database. • The rollback() method is used to undo the effect of all the SQL operations performed after the last commit operation. • A batch is a group of update statements that are sent to a database to be executed as a single unit. You send the batch to a database as a single request using the same Connection object. • The executeBatch() method returns an integer array that stores the update count for all the SQL statements that are executed successfully in a batch. The update count is the number of database rows affected by the database operation performed by each SQL statement. • Batch update operations can throw two types of exceptions, SQLException and BatchUpdateException. • The SQLException is thrown when the database access problem occurs. The SQLException is also thrown when a SELECT statement that returns a ResultSet object is executed in a batch. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 43 of 45
  • 44. Creating Applications Using Advanced Features of JDBC Summary (Contd.) • The BatchUpdateException is thrown when the SQL statement in the batch cannot be executed due to the problem in accessing the specified table or presence of illegal arguments in the SQL statement. • The CallableStatement interface contains various methods that enable you to call the stored procedures from a database. • The parameters of a stored procedure can take any of these three forms: • IN: Refers to the argument that you pass to a stored procedure. • OUT: Refers to the return value of a stored procedure. • INOUT: Enables you pass an argument to a stored procedure. The same parameters can also be used to pass a return value of a stored procedure. • Metadata is the information about data, such as structure and properties of table. • JDBC API provides two metadata interfaces to retrieve the information about the database and result set, DatabaseMetaData and ResultSetMetaData. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 44 of 45
  • 45. Creating Applications Using Advanced Features of JDBC Summary (Contd.) • The DatabaseMetaData interface declares methods that enable you to determine the properties of a database or RDBMS. • The ResultSetMetaData interface declares methods that enable you to determine information about data in a result set. • The getMetaData() method of the Connection interface enables you to declare the objects of the DatabaseMetaData interface. The methods in the DatabaseMetaData interface retrieve information only about the database to which a Java application is connected. • The getMetaData() method of the ResultSet interface enables you to create the instance of the ResultSetMetaData interface. ©NIIT JDBC and JavaBeans Lesson 1B / Slide 45 of 45