SlideShare a Scribd company logo
1 of 43
Java Programming Language
Objectives


                In this session, you will learn to:
                   Create applications using the PreparedStatement object
                   Manage database transactions
                   Perform batch updates
                   Create and call stored procedures in JDBC
                   Use metadata in JDBC




     Ver. 1.0                        Session 10                         Slide 1 of 43
Java Programming Language
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.




    Ver. 1.0                      Session 10                          Slide 2 of 43
Java Programming Language
Methods of the PreparedStatement Interface


               • The PreparedStatement interface inherits the following
                 methods to execute SQL statements from the Statement
                 interface:
                  – Allows you to pass runtime parameters to the SQL statements
                    to query and modify the data in a table.
                  – 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.




    Ver. 1.0                         Session 10                          Slide 3 of 43
Java Programming Language
Methods of the PreparedStatement Interface (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 = ?");




     Ver. 1.0                        Session 10                       Slide 4 of 43
Java Programming Language
Methods of the PreparedStatement Interface (Contd.)


               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();




    Ver. 1.0                      Session 10                       Slide 5 of 43
Java Programming Language
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();




    Ver. 1.0                        Session 10                      Slide 6 of 43
Java Programming Language
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();




    Ver. 1.0                      Session 10                         Slide 7 of 43
Java Programming Language
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();




    Ver. 1.0                     Session 10                       Slide 8 of 43
Java Programming Language
Updating and Deleting Rows (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();




    Ver. 1.0                         Session 10                       Slide 9 of 43
Java Programming Language
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.




    Ver. 1.0                       Session 10                                Slide 10 of 43
Java Programming Language
Demonstration (Contd.)


                The user interface of the application should be as shown in
                the following figure:




    Ver. 1.0                   Session 10                            Slide 11 of 43
Java Programming Language
Demonstration (Contd.)


               Solution:
                   The user interface of the application should be as shown in the
                   following figure:
                   –     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.




    Ver. 1.0                   Session 10                                Slide 12 of 43
Java Programming Language
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.




    Ver. 1.0                      Session 10                          Slide 13 of 43
Java Programming Language
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);




    Ver. 1.0                         Session 10                           Slide 14 of 43
Java Programming Language
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.




    Ver. 1.0                     Session 10                        Slide 15 of 43
Java Programming Language
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.




    Ver. 1.0                     Session 10                           Slide 16 of 43
Java Programming Language
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.




    Ver. 1.0                       Session 10                              Slide 17 of 43
Java Programming Language
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.




    Ver. 1.0                        Session 10                      Slide 18 of 43
Java Programming Language
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();



    Ver. 1.0                        Session 10                       Slide 19 of 43
Java Programming Language
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.




    Ver. 1.0                      Session 10                            Slide 20 of 43
Java Programming Language
Performing Batch Updates (Contd.)


               •   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.




    Ver. 1.0                          Session 10                         Slide 21 of 43
Java Programming Language
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.




    Ver. 1.0                        Session 10                       Slide 22 of 43
Java Programming Language
Creating and Calling Stored Procedures in JDBC (Contd.)


               Creating Stored Procedure:
               –   Can be created using the CREATE PROCEDURE SQL
                   statement in JDBC applications.
               –   Are of two types:
                      Parameterized
                      Non-parameterized




    Ver. 1.0                     Session 10                        Slide 23 of 43
Java Programming Language
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.




    Ver. 1.0                     Session 10                            Slide 24 of 43
Java Programming Language
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> };




    Ver. 1.0                      Session 10                            Slide 25 of 43
Java Programming Language
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>]}




    Ver. 1.0                    Session 10                         Slide 26 of 43
Java Programming Language
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>);




    Ver. 1.0                        Session 10                       Slide 27 of 43
Java Programming Language
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)




    Ver. 1.0                        Session 10                      Slide 28 of 43
Java Programming Language
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




    Ver. 1.0                       Session 10                           Slide 29 of 43
Java Programming Language
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();




    Ver. 1.0                          Session 10                           Slide 30 of 43
Java Programming Language
Using Metadata in JDBC (Contd.)


                The following table lists the commonly used methods of the
                DatabaseMetaData interface:


                            Method                              Description


               ResultSet getColumns(String        Retrieves the information about a
               catalog, String schema, String     column of a database table that is
               table_name, 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.



    Ver. 1.0                         Session 10                                Slide 31 of 43
Java Programming Language
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      primary keys of the database tables.
               table)
               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.



    Ver. 1.0                          Session 10                               Slide 32 of 43
Java Programming Language
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();




    Ver. 1.0                         Session 10                            Slide 33 of 43
Java Programming Language
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                       Retrieves the title of the table column corresponding
               getColumnLabel(int           to the index passed as a parameter to this method.
               column_index)
               String                       Retrieves the name of the table column
               getColumnName(int            corresponding to the index passed as a parameter
               column_index)                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.




    Ver. 1.0                           Session 10                                     Slide 34 of 43
Java Programming Language
Using Metadata in JDBC (Contd.)


                 The methods of the ResultSetMetaData interface:
                 (Contd.)
                       Method                                Description



               String                     Retrieves the name of the database table that
               getTableName(int           contains the column corresponding to the index
               column_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.




    Ver. 1.0                         Session 10                                    Slide 35 of 43
Java Programming Language
Using Metadata in JDBC (Contd.)


               •     The methods of the ResultSetMetaData interface:
                     (Contd.)

                             Method                                      Description



                   boolean isReadOnly(int                Returns a boolean value that indicates whether
                   column_index)                         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 whether
                   column_index)                         ResultSet column corresponding to the index
                                                         passed as a parameter is updatable.




    Ver. 1.0                                Session 10                                      Slide 36 of 43
Java Programming Language
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.




    Ver. 1.0                       Session 10                               Slide 37 of 43
Java Programming Language
Demonstration (Contd.)


               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:
                             1. Code the application.
                             2. Compile and execute the application.




    Ver. 1.0                       Session 10                                Slide 38 of 43
Java Programming Language
Summary


              In this lesson, you have 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.



   Ver. 1.0                       Session 10                            Slide 39 of 43
Java Programming Language
Summary (Contd.)


               –   If the setAutoCommit() method is set to true the database
                   operations performed by the SQL statements are
                   automatically committed in the database.
               –   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.

    Ver. 1.0                      Session 10                          Slide 40 of 43
Java Programming Language
Summary (Contd.)


               –   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.
               –   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.




    Ver. 1.0                       Session 10                            Slide 41 of 43
Java Programming Language
Summary (Contd.)


                   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.
               –   The DatabaseMetaData interface declares methods that
                   enable you to determine the properties of a database or
                   RDBMS.


    Ver. 1.0                       Session 10                                Slide 42 of 43
Java Programming Language
Summary (Contd.)


               –   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 getMetaData() method of the ResultSet interface
                   enables you to create the instance of the
                   ResultSetMetaData interface.




    Ver. 1.0                       Session 10                            Slide 43 of 43

More Related Content

What's hot

What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 
Centralized Server Manager
Centralized Server ManagerCentralized Server Manager
Centralized Server ManagerA R
 
Java session04
Java session04Java session04
Java session04Niit Care
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsTonny Madsen
 
J2 Se 5.0 Name And Version Change
J2 Se 5.0 Name And Version ChangeJ2 Se 5.0 Name And Version Change
J2 Se 5.0 Name And Version Changewhite paper
 
L0036 - Creating Views and Editors
L0036 - Creating Views and EditorsL0036 - Creating Views and Editors
L0036 - Creating Views and EditorsTonny Madsen
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitTonny Madsen
 
02.egovFrame Development Environment training book
02.egovFrame Development Environment training book02.egovFrame Development Environment training book
02.egovFrame Development Environment training bookChuong Nguyen
 
Db2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windowsDb2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windowsbupbechanhgmail
 
Java session16
Java session16Java session16
Java session16Niit Care
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)Narayana Swamy
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 

What's hot (20)

What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Centralized Server Manager
Centralized Server ManagerCentralized Server Manager
Centralized Server Manager
 
Java session04
Java session04Java session04
Java session04
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
J2 Se 5.0 Name And Version Change
J2 Se 5.0 Name And Version ChangeJ2 Se 5.0 Name And Version Change
J2 Se 5.0 Name And Version Change
 
L0036 - Creating Views and Editors
L0036 - Creating Views and EditorsL0036 - Creating Views and Editors
L0036 - Creating Views and Editors
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget Toolkit
 
Cnc scala-presentation
Cnc scala-presentationCnc scala-presentation
Cnc scala-presentation
 
02.egovFrame Development Environment training book
02.egovFrame Development Environment training book02.egovFrame Development Environment training book
02.egovFrame Development Environment training book
 
Db2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windowsDb2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windows
 
Java session16
Java session16Java session16
Java session16
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Javabeans .pdf
Javabeans .pdfJavabeans .pdf
Javabeans .pdf
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Image Converter
Image ConverterImage Converter
Image Converter
 

Viewers also liked

Aae oop xp_04
Aae oop xp_04Aae oop xp_04
Aae oop xp_04Niit Care
 
Aae oop xp_09
Aae oop xp_09Aae oop xp_09
Aae oop xp_09Niit Care
 
Java session13
Java session13Java session13
Java session13Niit Care
 
Chapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionChapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionIt Academy
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statementsjyoti_lakhani
 
Aae oop xp_08
Aae oop xp_08Aae oop xp_08
Aae oop xp_08Niit Care
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetitionOnline
 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 

Viewers also liked (14)

Aae oop xp_04
Aae oop xp_04Aae oop xp_04
Aae oop xp_04
 
Aae oop xp_09
Aae oop xp_09Aae oop xp_09
Aae oop xp_09
 
Java session13
Java session13Java session13
Java session13
 
Inheritance
InheritanceInheritance
Inheritance
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Chapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionChapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class Construction
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
 
Aae oop xp_08
Aae oop xp_08Aae oop xp_08
Aae oop xp_08
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetition
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Variable scope
Variable scopeVariable scope
Variable scope
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 

Similar to Java session17

Java session01
Java session01Java session01
Java session01Niit Care
 
JSF basics
JSF basicsJSF basics
JSF basicsairbo
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.ppt41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.pptMohammedNouh7
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineGil Fink
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
MarvelSoft SchoolAdmin Dev Framework
MarvelSoft SchoolAdmin Dev FrameworkMarvelSoft SchoolAdmin Dev Framework
MarvelSoft SchoolAdmin Dev FrameworkRanganath Shivaram
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enGeorge Birbilis
 

Similar to Java session17 (20)

Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Java session01
Java session01Java session01
Java session01
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Lecture17
Lecture17Lecture17
Lecture17
 
Select query in JDBC
Select query in JDBCSelect query in JDBC
Select query in JDBC
 
JSF basics
JSF basicsJSF basics
JSF basics
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.ppt41slideAdvancedDatabaseProgramming.ppt
41slideAdvancedDatabaseProgramming.ppt
 
11. jdbc
11. jdbc11. jdbc
11. jdbc
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Csharp dot net
Csharp dot netCsharp dot net
Csharp dot net
 
Oop lec 1
Oop lec 1Oop lec 1
Oop lec 1
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
MarvelSoft SchoolAdmin Dev Framework
MarvelSoft SchoolAdmin Dev FrameworkMarvelSoft SchoolAdmin Dev Framework
MarvelSoft SchoolAdmin Dev Framework
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_en
 

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-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-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
 

Recently uploaded

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 

Recently uploaded (20)

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 

Java session17

  • 1. Java Programming Language Objectives In this session, you will learn to: Create applications using the PreparedStatement object Manage database transactions Perform batch updates Create and call stored procedures in JDBC Use metadata in JDBC Ver. 1.0 Session 10 Slide 1 of 43
  • 2. Java Programming Language 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. Ver. 1.0 Session 10 Slide 2 of 43
  • 3. Java Programming Language Methods of the PreparedStatement Interface • The PreparedStatement interface inherits the following methods to execute SQL statements from the Statement interface: – Allows you to pass runtime parameters to the SQL statements to query and modify the data in a table. – 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. Ver. 1.0 Session 10 Slide 3 of 43
  • 4. Java Programming Language Methods of the PreparedStatement Interface (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 = ?"); Ver. 1.0 Session 10 Slide 4 of 43
  • 5. Java Programming Language Methods of the PreparedStatement Interface (Contd.) 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(); Ver. 1.0 Session 10 Slide 5 of 43
  • 6. Java Programming Language 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(); Ver. 1.0 Session 10 Slide 6 of 43
  • 7. Java Programming Language 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(); Ver. 1.0 Session 10 Slide 7 of 43
  • 8. Java Programming Language 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(); Ver. 1.0 Session 10 Slide 8 of 43
  • 9. Java Programming Language Updating and Deleting Rows (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(); Ver. 1.0 Session 10 Slide 9 of 43
  • 10. Java Programming Language 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. Ver. 1.0 Session 10 Slide 10 of 43
  • 11. Java Programming Language Demonstration (Contd.) The user interface of the application should be as shown in the following figure: Ver. 1.0 Session 10 Slide 11 of 43
  • 12. Java Programming Language Demonstration (Contd.) Solution: The user interface of the application should be as shown in the following figure: – 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. Ver. 1.0 Session 10 Slide 12 of 43
  • 13. Java Programming Language 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. Ver. 1.0 Session 10 Slide 13 of 43
  • 14. Java Programming Language 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); Ver. 1.0 Session 10 Slide 14 of 43
  • 15. Java Programming Language 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. Ver. 1.0 Session 10 Slide 15 of 43
  • 16. Java Programming Language 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. Ver. 1.0 Session 10 Slide 16 of 43
  • 17. Java Programming Language 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. Ver. 1.0 Session 10 Slide 17 of 43
  • 18. Java Programming Language 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. Ver. 1.0 Session 10 Slide 18 of 43
  • 19. Java Programming Language 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(); Ver. 1.0 Session 10 Slide 19 of 43
  • 20. Java Programming Language 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. Ver. 1.0 Session 10 Slide 20 of 43
  • 21. Java Programming Language Performing Batch Updates (Contd.) • 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. Ver. 1.0 Session 10 Slide 21 of 43
  • 22. Java Programming Language 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. Ver. 1.0 Session 10 Slide 22 of 43
  • 23. Java Programming Language Creating and Calling Stored Procedures in JDBC (Contd.) Creating Stored Procedure: – Can be created using the CREATE PROCEDURE SQL statement in JDBC applications. – Are of two types: Parameterized Non-parameterized Ver. 1.0 Session 10 Slide 23 of 43
  • 24. Java Programming Language 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. Ver. 1.0 Session 10 Slide 24 of 43
  • 25. Java Programming Language 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> }; Ver. 1.0 Session 10 Slide 25 of 43
  • 26. Java Programming Language 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>]} Ver. 1.0 Session 10 Slide 26 of 43
  • 27. Java Programming Language 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>); Ver. 1.0 Session 10 Slide 27 of 43
  • 28. Java Programming Language 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) Ver. 1.0 Session 10 Slide 28 of 43
  • 29. Java Programming Language 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 Ver. 1.0 Session 10 Slide 29 of 43
  • 30. Java Programming Language 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(); Ver. 1.0 Session 10 Slide 30 of 43
  • 31. Java Programming Language Using Metadata in JDBC (Contd.) The following table lists the commonly used methods of the DatabaseMetaData interface: Method Description ResultSet getColumns(String Retrieves the information about a catalog, String schema, String column of a database table that is table_name, 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. Ver. 1.0 Session 10 Slide 31 of 43
  • 32. Java Programming Language 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 primary keys of the database tables. table) 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. Ver. 1.0 Session 10 Slide 32 of 43
  • 33. Java Programming Language 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(); Ver. 1.0 Session 10 Slide 33 of 43
  • 34. Java Programming Language 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 Retrieves the title of the table column corresponding getColumnLabel(int to the index passed as a parameter to this method. column_index) String Retrieves the name of the table column getColumnName(int corresponding to the index passed as a parameter column_index) 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. Ver. 1.0 Session 10 Slide 34 of 43
  • 35. Java Programming Language Using Metadata in JDBC (Contd.) The methods of the ResultSetMetaData interface: (Contd.) Method Description String Retrieves the name of the database table that getTableName(int contains the column corresponding to the index column_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. Ver. 1.0 Session 10 Slide 35 of 43
  • 36. Java Programming Language Using Metadata in JDBC (Contd.) • The methods of the ResultSetMetaData interface: (Contd.) Method Description boolean isReadOnly(int Returns a boolean value that indicates whether column_index) 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 whether column_index) ResultSet column corresponding to the index passed as a parameter is updatable. Ver. 1.0 Session 10 Slide 36 of 43
  • 37. Java Programming Language 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. Ver. 1.0 Session 10 Slide 37 of 43
  • 38. Java Programming Language Demonstration (Contd.) 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: 1. Code the application. 2. Compile and execute the application. Ver. 1.0 Session 10 Slide 38 of 43
  • 39. Java Programming Language Summary In this lesson, you have 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. Ver. 1.0 Session 10 Slide 39 of 43
  • 40. Java Programming Language Summary (Contd.) – If the setAutoCommit() method is set to true the database operations performed by the SQL statements are automatically committed in the database. – 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. Ver. 1.0 Session 10 Slide 40 of 43
  • 41. Java Programming Language Summary (Contd.) – 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. – 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. Ver. 1.0 Session 10 Slide 41 of 43
  • 42. Java Programming Language Summary (Contd.) 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. – The DatabaseMetaData interface declares methods that enable you to determine the properties of a database or RDBMS. Ver. 1.0 Session 10 Slide 42 of 43
  • 43. Java Programming Language Summary (Contd.) – 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 getMetaData() method of the ResultSet interface enables you to create the instance of the ResultSetMetaData interface. Ver. 1.0 Session 10 Slide 43 of 43