JAVA Session17

Embed Size (px)

Citation preview

  • 8/8/2019 JAVA Session17

    1/43

  • 8/8/2019 JAVA Session17

    2/43

    Slide 2 of 43Session 10Ver. 1.0

    Java Programming Language

    T he PreparedStatement interface is derived from theStatement interface and is available in the java.sqlpackage.T he PreparedStatement object:

    Allows you to pass runtime parameters to the SQL statementsto query and modify the data in a table.Is compiled and prepared only once by JDBC. T he futureinvocation of the PreparedStatement object does notrecompile the SQL statements.Helps in reducing the load on the database server and thusimproving the performance of the application.

    Q uerying and Modifying Data Using the PreparedStatement Obj ect

  • 8/8/2019 JAVA Session17

    3/43

    Slide 3 of 43Session 10Ver. 1.0

    Java Programming Language

    T he PreparedStatement interface inherits the followingmethods to execute SQL statements from the Statementinterface:

    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 returnsa boolean value.

    Methods of the PreparedStatement Interface

  • 8/8/2019 JAVA Session17

    4/43

    Slide 4 of 43Session 10Ver. 1.0

    Java Programming Language

    T he prepareStatement() method of the Connectionobject is used to submit parameterized query to a database.T he SQL statement can contain ? symbol as placeholdersthat can be replaced by input parameters at runtime. For

    example:stat=con.prepareStatement("SELECT * FROMauthors WHERE au_id = ?");

    Methods of the PreparedStatement Interface (Contd.)

  • 8/8/2019 JAVA Session17

    5/43

    Slide 5 of 43Session 10Ver. 1.0

    Java Programming Language

    T he value of each ? parameter is set by calling anappropriate setXXX() method, where xxx is the data type of the parameter. For example:stat.setString(1,"1001");

    ResultSet result=stat.executeQuery();

    Methods of the PreparedStatement Interface (Contd.)

  • 8/8/2019 JAVA Session17

    6/43

    Slide 6 of 43Session 10Ver. 1.0

    Java Programming Language

    T he code snippet to retrieve books written by an author from the titles table using the PreparedStatement objectis:String str = "SELECT * FROM titles WHERE

    au_id = ?";PreparedStatement ps=

    con.prepareStatement(str);ps.setString(1, "1001");ResultSet rs=ps.executeQuery();

    R etrieving R ows

  • 8/8/2019 JAVA Session17

    7/43

    Slide 7 of 43Session 10Ver. 1.0

    Java Programming Language

    T he code snippet to create a PreparedStatement objectthat inserts a row into authors table by passing authors dataat 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();

    Inserting R ows

  • 8/8/2019 JAVA Session17

    8/43

    Slide 8 of 43Session 10Ver. 1.0

    Java Programming Language

    T he code snippet to modify the state to CA where city isOakland in the authors table using thePreparedStatement 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();

    Updating and Deleting R ows

  • 8/8/2019 JAVA Session17

    9/43

    Slide 9 of 43Session 10Ver. 1.0

    Java Programming Language

    T he code snippet to delete a row from the authors tablewhere authors first name is Abraham using thePreparedStatement object is:String str = "DELETE FROM authors WHERE

    au_fname= ? ";PreparedStatement ps =con.prepareStatement(str);ps.setString(1, "Abraham");int rt=ps.executeUpdate();

    Updating and Deleting R ows (Contd.)

  • 8/8/2019 JAVA Session17

    10/43

    Slide 10 of 43Session 10Ver. 1.0

    Java Programming Language

    Creating an Application that Uses PreparedStatementObject:

    Problem Statement:T he management of a departmental store has decided to

    computerize the inventory. You have been asked to create theProduct Information application that has an interactive user interface. T he application should allow the user to add, update,and delete product information from the product table.

    Demonstration

  • 8/8/2019 JAVA Session17

    11/43

    Slide 11 of 43Session 10Ver. 1.0

    Java Programming Language

    T he user interface of the application should be as shown inthe following figure:

    Demonstration (Contd.)

  • 8/8/2019 JAVA Session17

    12/43

    Slide 12 of 43Session 10Ver. 1.0

    Java Programming Language

    Solution:T he user interface of the application should be as shown in thefollowing figure:

    T he GUI for the application is created using thejava.swing package. T he database operations are

    performed using the PreparedStatement objectTo solve the above problem, perform the following tasks:

    Code the application.Compile and execute the application.

    Demonstration (Contd.)

  • 8/8/2019 JAVA Session17

    13/43

    Slide 13 of 43Session 10Ver. 1.0

    Java Programming Language

    A transaction:Is a set of one or more SQL statements that are executed asa single unit.Is complete only when all the SQL statements in a

    transaction execute successfully.Maintains consistency of data in a database.

    Managing Data b ase Transactions

  • 8/8/2019 JAVA Session17

    14/43

    Slide 14 of 43Session 10Ver. 1.0

    Java Programming Language

    JDBC API provides support for transaction management.T he database transactions can be committed in two ways in

    the JDBC applications:Implicit: T he Connection object uses the auto-commit

    mode to execute the SQL statements implicitly.Explicit: T he auto-commit mode is set to false tocommit the transaction statement explicitly. T he methodcall to set the auto-commit mode to false is:con.setAutoCommit(false);

    Managing Data b ase Transactions (Contd.)

  • 8/8/2019 JAVA Session17

    15/43

    Slide 15 of 43Session 10Ver. 1.0

    Java Programming Language

    Committing a T ransaction:T he commit() method is used to reflect the changes made bythe transactions in a database.T he 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.

    Managing Data b ase Transactions (Contd.)

  • 8/8/2019 JAVA Session17

    16/43

    Slide 16 of 43Session 10Ver. 1.0

    Java Programming Language

    A batch:Is a group of update statements that are sent to a databaseto 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 asingle SQL statement.

    Performing Batch Updates

  • 8/8/2019 JAVA Session17

    17/43

    Slide 17 of 43Session 10Ver. 1.0

    Java Programming Language

    Implementing Batch Updates in JDBC:T he Statement or PreparedStatement interface providesthe following methods to create and execute a batch of SQLstatements:

    void addBatch() : Adds an SQL statement to a batch.int executeBatch() : Sends a batch of SQL statements to adatabase for processing and returns the total number of therows updated.void clearBatch() : Removes the SQL statements from thebatch.

    Performing Batch Updates (Contd.)

  • 8/8/2019 JAVA Session17

    18/43

    Slide 18 of 43Session 10Ver. 1.0

    Java Programming Language

    W hen a Statement object is created to perform batchupdates, an empty array is associated with the object.Multiple SQL statements can be added to the empty arrayto execute them as a batch.

    You also need to disable the auto-commit mode usingsetAutoCommit(false) while working with batchupdates in JDBC.T he executeBatch() method returns an integer arraythat stores the values of the update count.

    T he update count is the total number of rows affected whenan SQL statement in a batch is processed.

    Performing Batch Updates (Contd.)

  • 8/8/2019 JAVA Session17

    19/43

    Slide 19 of 43Session 10Ver. 1.0

    Java Programming Language

    T he 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')");

    T he SQL statements in a batch are processed in the order

    in which the statements appear in a batch.T he method call to execute a batch of SQL statements is:int[] updcount=state.executeBatch();

    Performing Batch Updates (Contd.)

  • 8/8/2019 JAVA Session17

    20/43

    Slide 20 of 43Session 10Ver. 1.0

    Java Programming Language

    Exception Handling in Batch Updates:T he batch update operations can throw two types of exceptions:

    SQLException

    BatchUpdateExceptionT he BatchUpdateException class is derived fromSQLException class.

    Performing Batch Updates (Contd.)

  • 8/8/2019 JAVA Session17

    21/43

    Slide 21 of 43Session 10Ver. 1.0

    Java Programming Language

    T he SQLException is thrown by the JDBC API methods,addBatch() or executeBatch() , when problem occurswhile accessing a database.T he BatchUpdateException exception is thrown when

    the SQL statements in the batch cannot be executed dueto:

    Presence of illegal arguments in the SQL statement. Absence of the database table from which you need toretrieve data.

    T heBatchUpdateException

    uses an array of theupdate count to identify the SQL statement that throws theexception.

    Performing Batch Updates (Contd.)

  • 8/8/2019 JAVA Session17

    22/43

    Slide 22 of 43Session 10Ver. 1.0

    Java Programming Language

    The java.sql package provides theCallableStatement interface that contains variousmethods to enable you to call the stored procedures from adatabase.

    The CallableStatement interface is derived from thePreparedStatement interface.

    Creating and Calling Stored Procedures in JDBC

  • 8/8/2019 JAVA Session17

    23/43

    Slide 23 of 43Session 10Ver. 1.0

    Java Programming Language

    Creating Stored Procedure:Can be created using the CREATE PROCEDURE SQLstatement in JDBC applications.

    Are of two types:

    ParameterizedNon-parameterized

    Creating and Calling Stored Procedures in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    24/43

    Slide 24 of 43Session 10Ver. 1.0

    Java Programming Language

    A parameterized stored procedure can accept one or multiple parameters.

    A parameter of a stored procedure can take any of theseforms:

    IN: Refers to the argument that you pass to a storedprocedure.OU T: Refers to the return value of a stored procedure.INOU T: Combines the functionality of the IN and OU T parameters. T he INOU T parameter enables you to pass anargument to a stored procedure. T he same parameter canalso be used to store a return value of a stored procedure.

    Creating and Calling Stored Procedures in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    25/43

    Slide 25 of 43Session 10Ver. 1.0

    Java Programming Language

    Calling a Stored Procedure without Parameters:T he Connection interface provides the prepareCall()method that is used to create the CallableStatementobject to call a stored procedure.T

    he prepareCall() has the following three forms:CallableStatement prepareCall(String str)CallableStatement prepareCall(String str, intresSetType, int resSetConcurrency)CallableStatement prepareCall(String str, intresSetType, int resSetConcurrency, intresSetHoldability)

    T he syntax to call a stored procedure without parameters is:{ call };

    Creating and Calling Stored Procedures in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    26/43

    Slide 26 of 43Session 10Ver. 1.0

    Java Programming Language

    Calling a Stored Procedure with Parameters:T he SQL escape syntax is a standard way to call a storedprocedure from a Relational Database Management System(RDBMS) and is independent of the RDBMS.T

    here are two forms of the SQL escape syntax, one thatcontains result parameter and one that does not.T he syntax of the SQL escape syntax is:{[? =] call

    [,, ...,]}

    Creating and Calling Stored Procedures in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    27/43

  • 8/8/2019 JAVA Session17

    28/43

    Slide 28 of 43Session 10Ver. 1.0

    Java Programming Language

    If the stored procedure contains OU T and INOU T parameters, these parameters should be registered withthe corresponding JDBC types.T he registerOut() method is used to register the

    parameters.T he prototypes of the registerOut() method are:

    registerOut(int index, int stype)

    registerOut(int index, int stype, int scale)

    Creating and Calling Stored Procedures in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    29/43

  • 8/8/2019 JAVA Session17

    30/43

    Slide 30 of 43Session 10Ver. 1.0

    Java Programming Language

    Using DatabaseMetaData Interface:T he DatabaseMetaData interface provides the methodsthat enable you to determine the properties of a database or RDBMS.

    An object of DatabaseMetaData

    is created using thegetMetaData() method of the Connection interface.T he method call to create an object of theDatabaseMetaData interface is:DatabaseMetaData dm=con.getMetaData();

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    31/43

    Slide 31 of 43Session 10Ver. 1.0

    Java Programming Language

    T he following table lists the commonly used methods of theDatabaseMetaData interface:

    M ethod Description

    ResultSet getColumns(Stringcatalog, String schema, Stringtable_name, String column_name)

    Retrieves the information about acolumn of a database table that isavailable in the specified catalog.

    Connection getConnection() Retrieves the database connection thatcreates the DatabaseMetaData object.

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

    String getDriverVersion() Retrieves the version of the JDBCdriver.

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    32/43

    Slide 32 of 43Session 10Ver. 1.0

    Java Programming Language

    T he methods of the DatabaseMetaData interface:(Contd.)

    M ethod Description

    ResultSet getPrimaryKeys(Stringcatalog, String schema, Stringtable)

    Retrieves the information about theprimary keys of the database tables.

    String getURL() Retrieves the URL of the database.

    boolean isReadOnly() Returns a boolean value that indicateswhether the database is a read onlydatabase.

    boolean supportsSavepoints() Returns a boolean value that indicateswhether the database supportssavepoints.

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    33/43

    Slide 33 of 43Session 10Ver. 1.0

    Java Programming Language

    Using the ReultSetMetaData Interface:T he ReultSetMetaData Interface contains variousmethods that enable you to retrieve information about thedata in a result set.T he ResultSet interface provides the getMetaData()method to create an object of the ResultSetMetaDatainterface.T he method call to create an object of theResultSetMetaData interface:ResultSetMetaData rm=rs.getMetaData();

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    34/43

    Slide 34 of 43Session 10Ver. 1.0

    Java Programming Language

    T he following table lists the commonly used methods of theResultSetMetaData interface:

    M ethod Description

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

    StringgetColumnLabel(intcolumn_index)

    Retrieves the title of the table column correspondingto the index passed as a parameter to this method.

    StringgetColumnName(intcolumn_index)

    Retrieves the name of the table columncorresponding to the index passed as a parameter tothis method.

    int getColumnType(intcolumn_index)

    Retrieves the SQL data type of the table columncorresponding to the index passed as a parameter.

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    35/43

    Slide 35 of 43Session 10Ver. 1.0

    Java Programming Language

    T he methods of the ResultSetMetaData interface:(Contd.)

    M ethod Description

    StringgetTableName(intcolumn_index)

    Retrieves the name of the database table thatcontains the column corresponding to the indexpassed as a parameter.

    booleanisAutoIncrement(intcolumn_index)

    Returns a boolean value that indicates whether thetable column corresponding to the index passed as aparameter increments automatically.

    booleanisCaseSensitive(intcolumn_index)

    Returns a boolean value that indicates whether thetable column corresponding to the index passed as aparameter is case sensitive.

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    36/43

    Slide 36 of 43Session 10Ver. 1.0

    Java Programming Language

    T he methods of the ResultSetMetaData interface:(Contd.)

    M ethod Description

    boolean isReadOnly(intcolumn_index)

    Returns a boolean value that indicates whether the column in a ResultSet corresponding to theindex passed as a parameter is read only.

    boolean isWritable(intcolumn_index) Returns a boolean value that indicates whether ResultSet column corresponding to the indexpassed as a parameter is updatable.

    Using Metadata in JDBC (Contd.)

  • 8/8/2019 JAVA Session17

    37/43

    Slide 37 of 43Session 10Ver. 1.0

    Java Programming Language

    Creating an Application to Retrieve the Information of Database Tables:

    Problem Statement:T he Manager of New Publishers publishing company,sometimes require the information about the tables of thedatabase used by the company. He is not familiar with the SQLstatements, therefore, he has asked you to create anapplication to determine the total number of columns and thedata types of the columns of a given table. T he table name hasto be specified at the runtime.

    Demonstration

  • 8/8/2019 JAVA Session17

    38/43

    Slide 38 of 43Session 10Ver. 1.0

    Java Programming Language

    Creating an Application to Retrieve the Information of Database Tables (Contd.)

    Solution:

    T he getColumnName(), getColumnCount(), andgetColumn T ypeName() methods of the ResultSetMetaDatainterface are used to develop the above application. To solvethe above problem, perform the following tasks:

    1. Code the application.2. Compile and execute the application.

    Demonstration (Contd.)

  • 8/8/2019 JAVA Session17

    39/43

    Slide 39 of 43Session 10Ver. 1.0

    Java Programming Language

    In this lesson, you have learned:T he PreparedStatement object of the Connectioninterface allows you to pass runtime parameters to the SQLstatements using the placeholders.T here can be multiple placeholders in a single SQLstatement. An index value is associated with eachplaceholder depending upon the position of the placeholder in the SQL statement.T he placeholder stores the value assigned to it until the valueis explicitly changed.

    A transaction is a set of one or more SQL statements that areexecuted as a single unit. A transaction is complete onlywhen all the SQL statements in a transaction are successfullyexecuted.

    Summary

  • 8/8/2019 JAVA Session17

    40/43

    Slide 40 of 43Session 10Ver. 1.0

    Java Programming Language

    If the setAutoCommit() method is set to true the databaseoperations performed by the SQL statements areautomatically committed in the database.T he commit() method reflects the changes made by theSQL statements permanently in the database.T he rollback() method is used to undo the effect of all theSQL operations performed after the last commit operation.

    A batch is a group of update statements that are sent to adatabase to be executed as a single unit. You send the batchto a database as a single request using the sameConnection object.T he executeBatch() method returns an integer array thatstores the update count for all the SQL statements that areexecuted successfully in a batch. T he update count is thenumber of database rows affected by the database operationperformed by each SQL statement.

    Summary (Contd.)

  • 8/8/2019 JAVA Session17

    41/43

    Slide 41 of 43Session 10Ver. 1.0

    Java Programming Language

    Batch update operations can throw two types of exceptions,SQLException and BatchUpdateException .T he SQLException is thrown when the database accessproblem occurs. T he SQLException is also thrown when aSELECT statement that returns a ResultSet object isexecuted in a batch.T he BatchUpdateException is thrown when the SQLstatement in the batch cannot be executed due to theproblem in accessing the specified table or presence of illegal arguments in the SQL statement.T he CallableStatement interface contains variousmethods that enable you to call the stored procedures from adatabase.

    Summary (Contd.)

  • 8/8/2019 JAVA Session17

    42/43

    Slide 42 of 43Session 10Ver. 1.0

    Java Programming Language

    T he parameters of a stored procedure can take any of thesethree forms:

    IN: Refers to the argument that you pass to a stored procedure.OU T: Refers to the return value of a stored procedure.INOU T: Enables you pass an argument to a stored procedure.T he same parameters can also be used to pass a return valueof a stored procedure.

    Metadata is the information about data, such as structure andproperties of table.JDBC API provides two metadata interfaces to retrieve theinformation about the database and result set,DatabaseMetaData and ResultSetMetaData .T he DatabaseMetaData interface declares methods thatenable you to determine the properties of a database or RDBMS.

    Summary (Contd.)

  • 8/8/2019 JAVA Session17

    43/43

    Slide 43 of 43Session 10Ver 1 0

    Java Programming Language

    Summary (Contd.)

    T he ResultSetMetaData interface declares methods thatenable you to determine information about data in a result set.T he getMetaData() method of the Connection interfaceenables you to declare the objects of theDatabaseMetaData interface.T he getMetaData() method of the ResultSet interfaceenables you to create the instance of theResultSetMetaData interface.