SlideShare a Scribd company logo
1 of 39
JDBC
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 2                          Slide 1 of 39
JDBC
Create Applications 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 2                          Slide 2 of 39
JDBC
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
                     statement 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.




     Ver. 1.0                         Session 2                          Slide 3 of 39
JDBC
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 2                       Slide 4 of 39
JDBC
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,β€œa001");
                 ResultSet result=stat.executeQuery();




     Ver. 1.0                      Session 2                        Slide 5 of 39
JDBC
Retrieving Rows


                β€’ The code snippet to retrieve books written by an author
                  from the books table using the PreparedStatement
                  object is:
                    String str = "SELECT * FROM books WHERE
                    au_id = ?";
                    PreparedStatement ps=
                    con.prepareStatement(str);
                    ps.setString(1, β€œa001");
                    ResultSet rs=ps.executeQuery();




     Ver. 1.0                         Session 2                       Slide 6 of 39
JDBC
Inserting Rows


                The code snippet to create a PreparedStatement object
                that inserts a row into authors table by passing authors data
                at run time is:
                 String str = "INSERT INTO Authors(au_id,
                 au_name) VALUES (?, ?)";
                 PreparedStatement ps =
                 con.prepareStatement(str);
                 ps.setString(1, β€œa001");
                 ps.setString(2, "Abraham White");
                 int rt=ps.executeUpdate();




     Ver. 1.0                       Session 2                         Slide 7 of 39
JDBC
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 2                        Slide 8 of 39
JDBC
Updating and Deleting Rows (Contd.)


                β€’ The code snippet to delete a row from the Authors table
                  where author’s name is Abraham White using the
                  PreparedStatement object is:
                   String str = "DELETE FROM Authors WHERE
                   au_name= ? ";
                   PreparedStatement ps =
                   con.prepareStatement(str);
                   ps.setString(1, "Abraham White");
                   int rt=ps.executeUpdate();




     Ver. 1.0                         Session 2                       Slide 9 of 39
JDBC
Just a minute


                Name the three methods of the PreparedStatement
                Interface.




                Answer:
                   The three methods of the PreparedStatement Interface are:
                    1. ResultSet executeQuery()
                    2. int executeUpdate()
                    3. Boolean execute()


     Ver. 1.0                       Session 2                          Slide 10 of 39
JDBC
Demonstration


               Problem Statement:
                  The management of the City Library has decided to
                  computerize the book inventory. You have been asked to
                  create the Publisher Information application that has an
                  interactive user interface. The application should allow the user
                  to add the details of the new publishers to the publishers table.




    Ver. 1.0                        Session 2                             Slide 11 of 39
JDBC
Demonstration (Contd.)


                A sample of the user interface is shown in the following fugure.




     Ver. 1.0                     Session 2                            Slide 12 of 39
JDBC
Demonstration (Contd.)


                To insert information about a new publisher in the publishers
                table:
                 1. Specify the id for a publisher in the ID textbox and publishers
                    details, such as name, phone, address, city, state, and zip in the
                    respective text boxes.
                 2. Click the Insert button to insert information.
                 3. To exit from the application, click the Exit button.




     Ver. 1.0                       Session 2                                 Slide 13 of 39
JDBC
Demonstration (Contd.)


                Solution:
                   To solve the problem, you need to perform the following tasks:
                    1. Code the application.
                    2. Compile and execute the application.




     Ver. 1.0                         Session 2                          Slide 14 of 39
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.




     Ver. 1.0                       Session 2                           Slide 15 of 39
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);




     Ver. 1.0                      Session 2                          Slide 16 of 39
JDBC
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 2                     Slide 17 of 39
JDBC
Just a minute


                How can you commit a transaction explicitly?




                Answer:
                   You can commit a transaction explicitly by setting auto-commit
                   mode to false.




     Ver. 1.0                       Session 2                            Slide 18 of 39
JDBC
Implementing Batch Updates in JDBC


                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 2                            Slide 19 of 39
JDBC
Implementing Batch Updates in JDBC (Contd.)


                β€’ 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 2                          Slide 20 of 39
JDBC
Implementing Batch Updates in JDBC (Contd.)


                The code snippet to create a batch of SQL statements is:
                 con.setAutoCommit(false);
                 Statement stmt=con.createStatement();
                 stmt.addBatch("INSERT INTO Publishers
                 (pub_id, pub_name) VALUES (β€˜p001’,β€˜Tate
                 Publishing')");
                 stmt.addBatch("INSERT INTO Publishers
                 (pub_id, pub_name) VALUES (β€˜p002’, β€˜Publish
                 America')");
                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=stmt.executeBatch();


     Ver. 1.0                     Session 2                      Slide 21 of 39
JDBC
Exception Handling in Batch Updates


                The batch update operations can throw two types of
                exceptions:
                   SQLException
                   BatchUpdateException
                    – The BatchUpdateException class is derived from the
                      SQLException class.




     Ver. 1.0                       Session 2                              Slide 22 of 39
JDBC
Exception Handling in 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 2                           Slide 23 of 39
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.




     Ver. 1.0                        Session 2                       Slide 24 of 39
JDBC
Creating Stored Procedures


                β€’ Can be created using the CREATE PROCEDURE SQL
                  statement in JDBC applications.
                β€’ Are of two types:
                     Parameterized
                     Non-parameterized




     Ver. 1.0                       Session 2                     Slide 25 of 39
JDBC
Creating Stored Procedures (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 2                         Slide 26 of 39
JDBC
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 2                        Slide 27 of 39
JDBC
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 2                      Slide 28 of 39
JDBC
Calling a Stored Procedure with Parameters (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 2                      Slide 29 of 39
JDBC
Calling a Stored Procedure with Parameters (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 2                       Slide 30 of 39
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




     Ver. 1.0                        Session 2                              Slide 31 of 39
JDBC
Using the 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 2                      Slide 32 of 39
JDBC
Using the ResultMetadata 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 2                        Slide 33 of 39
JDBC
Just a minute


                What are the metadata interfaces used to retrieve
                information about the database and result set?




                Answer:
                   The metadata interfaces used to retrieve information about the
                   database and result set are:
                    1. DatabaseMetaData interface
                    2. ResultSetMetaData interface


     Ver. 1.0                       Session 2                            Slide 34 of 39
JDBC
Demonstration


               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 run time.




    Ver. 1.0                       Session 2                           Slide 35 of 39
JDBC
Demonstration (Contd.)


                Solution:
                   To solve the Preceding problem, perform the following tasks:
                    1. Code the application.
                    2. Pass the command line argument.
                    3. Compile and execute the application.




     Ver. 1.0                         Session 2                          Slide 36 of 39
JDBC
Summary


               In this session, you learned that:
                – The PreparedStatement object 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.


    Ver. 1.0                        Session 2                            Slide 37 of 39
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.
               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.



    Ver. 1.0                    Session 2                          Slide 38 of 39
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.
               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




    Ver. 1.0                    Session 2                           Slide 39 of 39

More Related Content

What's hot

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connectionWaheed Warraich
Β 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...Pallepati Vasavi
Β 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05Ankit Dubey
Β 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database ConnectivityInformation Technology
Β 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
Β 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical filevarun arora
Β 
JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?gedoplan
Β 
Sql server
Sql serverSql server
Sql serverPuja Gupta
Β 
JDBC ppt
JDBC pptJDBC ppt
JDBC pptRohit Jain
Β 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQLAdil Mehmoood
Β 
All adapterscommonproperties
All adapterscommonpropertiesAll adapterscommonproperties
All adapterscommonpropertiesXAVIERCONSULTANTS
Β 

What's hot (16)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
Β 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
Β 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Β 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
Β 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Β 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Β 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
Β 
Jdbc
JdbcJdbc
Jdbc
Β 
JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?
Β 
Sql server
Sql serverSql server
Sql server
Β 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
Β 
Jdbc
JdbcJdbc
Jdbc
Β 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Β 
Jdbc
JdbcJdbc
Jdbc
Β 
All adapterscommonproperties
All adapterscommonpropertiesAll adapterscommonproperties
All adapterscommonproperties
Β 
Jdbc api
Jdbc apiJdbc api
Jdbc api
Β 

Viewers also liked

Java session05
Java session05Java session05
Java session05Niit Care
Β 
Java session02
Java session02Java session02
Java session02Niit Care
Β 
Java session11
Java session11Java session11
Java session11Niit Care
Β 
Java session08
Java session08Java session08
Java session08Niit Care
Β 
Dacj 1-1 b
Dacj 1-1 bDacj 1-1 b
Dacj 1-1 bNiit Care
Β 
NIIT Presentation 1
NIIT Presentation 1NIIT Presentation 1
NIIT Presentation 1NIIT Bahrain
Β 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 bNiit Care
Β 

Viewers also liked (7)

Java session05
Java session05Java session05
Java session05
Β 
Java session02
Java session02Java session02
Java session02
Β 
Java session11
Java session11Java session11
Java session11
Β 
Java session08
Java session08Java session08
Java session08
Β 
Dacj 1-1 b
Dacj 1-1 bDacj 1-1 b
Dacj 1-1 b
Β 
NIIT Presentation 1
NIIT Presentation 1NIIT Presentation 1
NIIT Presentation 1
Β 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
Β 

Similar to Jdbc session02

Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)Maher Abdo
Β 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-bNiit Care
Β 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-cNiit Care
Β 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1Tuan Ngo
Β 
Select query in JDBC
Select query in JDBCSelect query in JDBC
Select query in JDBCMaulik Togadiya
Β 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBCDudy Ali
Β 
Jdbc
Jdbc   Jdbc
Jdbc Ishucs
Β 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-aNiit Care
Β 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
Β 
Jdbc
JdbcJdbc
JdbcIshucs
Β 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
Β 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
Β 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
Β 

Similar to Jdbc session02 (20)

JDBC
JDBCJDBC
JDBC
Β 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Β 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
Β 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
Β 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
Β 
Select query in JDBC
Select query in JDBCSelect query in JDBC
Select query in JDBC
Β 
Jdbc
JdbcJdbc
Jdbc
Β 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
Β 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBC
Β 
Jdbc
Jdbc   Jdbc
Jdbc
Β 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
Β 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
Β 
Jdbc
JdbcJdbc
Jdbc
Β 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Β 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
Β 
Jdbc
JdbcJdbc
Jdbc
Β 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
Β 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
Β 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
Β 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
Β 

More from Niit Care

Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 bNiit Care
Β 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 aNiit Care
Β 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 cNiit Care
Β 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 bNiit Care
Β 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 aNiit Care
Β 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 cNiit Care
Β 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 bNiit Care
Β 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 aNiit Care
Β 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 cNiit Care
Β 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 aNiit Care
Β 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 cNiit Care
Β 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-cNiit Care
Β 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-bNiit Care
Β 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-aNiit Care
Β 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 bNiit Care
Β 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 cNiit Care
Β 
Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 bNiit Care
Β 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 aNiit Care
Β 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 cNiit Care
Β 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 aNiit Care
Β 

More from Niit Care (20)

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 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
Β 

Recently uploaded

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
Β 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
Β 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
Β 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
Β 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
Β 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
Β 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
Β 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
Β 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
Β 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
Β 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
Β 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
Β 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
Β 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
Β 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
Β 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Β 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
Β 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
Β 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
Β 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
Β 

Recently uploaded (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
Β 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
Β 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
Β 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
Β 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
Β 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
Β 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Β 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
Β 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Β 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
Β 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
Β 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Β 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Β 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
Β 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Β 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Β 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Β 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
Β 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
Β 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
Β 

Jdbc session02

  • 1. JDBC 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 2 Slide 1 of 39
  • 2. JDBC Create Applications 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 2 Slide 2 of 39
  • 3. JDBC 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 statement 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. Ver. 1.0 Session 2 Slide 3 of 39
  • 4. JDBC 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 2 Slide 4 of 39
  • 5. JDBC 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,β€œa001"); ResultSet result=stat.executeQuery(); Ver. 1.0 Session 2 Slide 5 of 39
  • 6. JDBC Retrieving Rows β€’ The code snippet to retrieve books written by an author from the books table using the PreparedStatement object is: String str = "SELECT * FROM books WHERE au_id = ?"; PreparedStatement ps= con.prepareStatement(str); ps.setString(1, β€œa001"); ResultSet rs=ps.executeQuery(); Ver. 1.0 Session 2 Slide 6 of 39
  • 7. JDBC Inserting Rows The code snippet to create a PreparedStatement object that inserts a row into authors table by passing authors data at run time is: String str = "INSERT INTO Authors(au_id, au_name) VALUES (?, ?)"; PreparedStatement ps = con.prepareStatement(str); ps.setString(1, β€œa001"); ps.setString(2, "Abraham White"); int rt=ps.executeUpdate(); Ver. 1.0 Session 2 Slide 7 of 39
  • 8. JDBC 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 2 Slide 8 of 39
  • 9. JDBC Updating and Deleting Rows (Contd.) β€’ The code snippet to delete a row from the Authors table where author’s name is Abraham White using the PreparedStatement object is: String str = "DELETE FROM Authors WHERE au_name= ? "; PreparedStatement ps = con.prepareStatement(str); ps.setString(1, "Abraham White"); int rt=ps.executeUpdate(); Ver. 1.0 Session 2 Slide 9 of 39
  • 10. JDBC Just a minute Name the three methods of the PreparedStatement Interface. Answer: The three methods of the PreparedStatement Interface are: 1. ResultSet executeQuery() 2. int executeUpdate() 3. Boolean execute() Ver. 1.0 Session 2 Slide 10 of 39
  • 11. JDBC Demonstration Problem Statement: The management of the City Library has decided to computerize the book inventory. You have been asked to create the Publisher Information application that has an interactive user interface. The application should allow the user to add the details of the new publishers to the publishers table. Ver. 1.0 Session 2 Slide 11 of 39
  • 12. JDBC Demonstration (Contd.) A sample of the user interface is shown in the following fugure. Ver. 1.0 Session 2 Slide 12 of 39
  • 13. JDBC Demonstration (Contd.) To insert information about a new publisher in the publishers table: 1. Specify the id for a publisher in the ID textbox and publishers details, such as name, phone, address, city, state, and zip in the respective text boxes. 2. Click the Insert button to insert information. 3. To exit from the application, click the Exit button. Ver. 1.0 Session 2 Slide 13 of 39
  • 14. JDBC Demonstration (Contd.) Solution: To solve the problem, you need to perform the following tasks: 1. Code the application. 2. Compile and execute the application. Ver. 1.0 Session 2 Slide 14 of 39
  • 15. 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. Ver. 1.0 Session 2 Slide 15 of 39
  • 16. 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); Ver. 1.0 Session 2 Slide 16 of 39
  • 17. JDBC 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 2 Slide 17 of 39
  • 18. JDBC Just a minute How can you commit a transaction explicitly? Answer: You can commit a transaction explicitly by setting auto-commit mode to false. Ver. 1.0 Session 2 Slide 18 of 39
  • 19. JDBC Implementing Batch Updates in JDBC 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 2 Slide 19 of 39
  • 20. JDBC Implementing Batch Updates in JDBC (Contd.) β€’ 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 2 Slide 20 of 39
  • 21. JDBC Implementing Batch Updates in JDBC (Contd.) The code snippet to create a batch of SQL statements is: con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.addBatch("INSERT INTO Publishers (pub_id, pub_name) VALUES (β€˜p001’,β€˜Tate Publishing')"); stmt.addBatch("INSERT INTO Publishers (pub_id, pub_name) VALUES (β€˜p002’, β€˜Publish America')"); 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=stmt.executeBatch(); Ver. 1.0 Session 2 Slide 21 of 39
  • 22. JDBC Exception Handling in Batch Updates The batch update operations can throw two types of exceptions: SQLException BatchUpdateException – The BatchUpdateException class is derived from the SQLException class. Ver. 1.0 Session 2 Slide 22 of 39
  • 23. JDBC Exception Handling in 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 2 Slide 23 of 39
  • 24. 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. Ver. 1.0 Session 2 Slide 24 of 39
  • 25. JDBC Creating Stored Procedures β€’ Can be created using the CREATE PROCEDURE SQL statement in JDBC applications. β€’ Are of two types: Parameterized Non-parameterized Ver. 1.0 Session 2 Slide 25 of 39
  • 26. JDBC Creating Stored Procedures (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 2 Slide 26 of 39
  • 27. JDBC 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 2 Slide 27 of 39
  • 28. JDBC 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 2 Slide 28 of 39
  • 29. JDBC Calling a Stored Procedure with Parameters (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 2 Slide 29 of 39
  • 30. JDBC Calling a Stored Procedure with Parameters (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 2 Slide 30 of 39
  • 31. 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 Ver. 1.0 Session 2 Slide 31 of 39
  • 32. JDBC Using the 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 2 Slide 32 of 39
  • 33. JDBC Using the ResultMetadata 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 2 Slide 33 of 39
  • 34. JDBC Just a minute What are the metadata interfaces used to retrieve information about the database and result set? Answer: The metadata interfaces used to retrieve information about the database and result set are: 1. DatabaseMetaData interface 2. ResultSetMetaData interface Ver. 1.0 Session 2 Slide 34 of 39
  • 35. JDBC Demonstration 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 run time. Ver. 1.0 Session 2 Slide 35 of 39
  • 36. JDBC Demonstration (Contd.) Solution: To solve the Preceding problem, perform the following tasks: 1. Code the application. 2. Pass the command line argument. 3. Compile and execute the application. Ver. 1.0 Session 2 Slide 36 of 39
  • 37. JDBC Summary In this session, you learned that: – The PreparedStatement object 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. Ver. 1.0 Session 2 Slide 37 of 39
  • 38. 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. 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. Ver. 1.0 Session 2 Slide 38 of 39
  • 39. 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. 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 Ver. 1.0 Session 2 Slide 39 of 39

Editor's Notes

  1. Reiterate the concepts taught earlier by asking the given question.
  2. Reiterate the concepts taught earlier by asking the given question.
  3. Reiterate the concepts taught earlier by asking the given question.