JDBC Final

download JDBC Final

of 55

Transcript of JDBC Final

  • 7/31/2019 JDBC Final

    1/55

    PreparedStatement

    CallableStatement

    ResultSetDatabase MetaData

  • 7/31/2019 JDBC Final

    2/55

    Packagejava.sql.PreparedStatement

    PreparedStatement(PS) Object is used toexecute the parametrized SQL statement.

    PS object supports zero or more INparameters.

    PS object represents a precompiled query that

    can be executed multiple times withoutcompiling again and again.

  • 7/31/2019 JDBC Final

    3/55

    PS object represent a pre-compiled SQLstatement, so that the execution of the SQLstatement is much faster as compared to theStatement object.

    java.sql.PreparedStatement is a subtype of thejava.sql.Statement interface, therefore it inheritsall the properties of the Statement interface.

  • 7/31/2019 JDBC Final

    4/55

    Important Points about PS are as follows:

    A PreparedStatement object is associated with aConnection object.

    A PS object represent the execution plan of anSQL statement saved into the database that is

    passed as a parameter while creating the PSobject.

    SQL statement can take parameters whosevalues can be set while operation.

    A PS is implicitly closed after the Connectionobject on which the PS object was created isclosed.

  • 7/31/2019 JDBC Final

    5/55

    ConnectionObject

    con

    Java Application JDBC Driver

    J V M

    3) Compile the givenSQL Statement

    4) Prepare anexecution plan toexecute the SQLstatement

    5) Store the executionplan with unique ID

    12) Locate theexecution plan

    13) Execute the planwith the given data

    2

    78

    1

    ps

    6

    PreparedStatement Object

    setXXX()

    executeXXX()

    911

    10

    15

    14

    result

    Steps involved in Using Prepared Statement

  • 7/31/2019 JDBC Final

    6/55

    set methods of PreparedStatement

    ReturnType

    Methods

    void setArray(int parameterIndex,Arrayx)

    Sets the designated parameter to the given java.sql.Array object.

    void setBinaryStream(int parameterIndex, InputStream x)Sets the designated parameter to the given input stream.

    void setBinaryStream(int parameterIndex, InputStream x, int length)Sets the designated parameter to the given input stream, which will have

    the specified number of bytes.void setBoolean(int parameterIndex, boolean x)

    Sets the designated parameter to the given Java boolean value.

    void setDate(int parameterIndex, Date x)

    void setDouble(int parameterIndex, double x)

    void setFloat(int parameterIndex, float x)

    void setInt(int parameterIndex, int x)

    void setLong(int parameterIndex, long x)

    void setObject(int parameterIndex, Object x)

    void setString(int parameterIndex, String x)

  • 7/31/2019 JDBC Final

    7/55

    It improves the performance of application, wheresame query is to be executed no. of times.

    It is easier to insert or update the SQL 99 datatype columns, such as BLOB, CLOB, or OBJECT

    It provides a programmatic approach to set thevalues of parameters in a more descriptive way.

  • 7/31/2019 JDBC Final

    8/55

    It can represent only one SQL statement.Therefore, we cannot execute more than onestatement by a single PreparedStatement.

    It supports to add only a single SQL statement tobe executed for multiple times with different set ofvalues it a batch.

  • 7/31/2019 JDBC Final

    9/55

  • 7/31/2019 JDBC Final

    10/55

    Broad level steps to use PreparedStatement:1. Create a PreparedStatement object

    2. Set the values for the Parameters3. Execute the PreparedStatement

    Creating a PreparedStatement object

    Created by using the prepareStatement(StringsqlStatement) method of the Connection object.

    Connection object submits the SQL statement, anddatabase returns an identity of the execution plan

    prepared for the SQL statement, if compilation wassuccessful.

    prepareStatement(String) method can contain a zeroor more question marks(?, known as prameters

  • 7/31/2019 JDBC Final

    11/55

    Values can be set for? after the SQL statement is

    compiled, i.e. after creating PS object or beforeexecuting the statement.

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

    Connection con =DriverManager.getConnection(url,user,password);

    String sqlSt = insert into mytable values(?,?,?);

    PreparedStatement ps = con.prepareStatement(sqlSt);

    //ps refers to the PS object created by using theConnection object.

  • 7/31/2019 JDBC Final

    12/55

    The PS object supports setter methods for allthe data types supported by Java.

    It accepts two argument. First, indicateparameter index. Second, indicates value for

    parameter.Eg:-

    ps.setString(1,abc1);ps.setInt(2,38);ps.setDouble(3,158.75);

    Note :- The parameter index starts from 1, fromleft to right of the statement.

  • 7/31/2019 JDBC Final

    13/55

    After preparing and initializing the PS object, wecan execute the SQL statement with theconfigured parameter.

    execute() returns boolean,

    executeUpdate() return int,executeQuery() returns ResultSet

    methods of the PS object are used to execute theSQL statement.

    int n = ps.executeUpdate();

    //n holds the no. of rows or tables that re beingupdate.

  • 7/31/2019 JDBC Final

    14/55

    Callable statement

  • 7/31/2019 JDBC Final

    15/55

    In java callable statement is used to call thestored procedures and functions.

    That is the procedure can be called by using anobject of the callablestatement interface.

    They are use ti access,invoke, and retrive the

    results of sql stored procedures,functions andcursors.

  • 7/31/2019 JDBC Final

    16/55

    Procedures

  • 7/31/2019 JDBC Final

    17/55

  • 7/31/2019 JDBC Final

    18/55

    Ussing callablestatement

  • 7/31/2019 JDBC Final

    19/55

  • 7/31/2019 JDBC Final

    20/55

  • 7/31/2019 JDBC Final

    21/55

  • 7/31/2019 JDBC Final

    22/55

  • 7/31/2019 JDBC Final

    23/55

  • 7/31/2019 JDBC Final

    24/55

    Calling Functions By UsingCallableStatement Most of the databases provide support for

    various types of built in functions.

    Some of these are:

    Numeric

    Strings

    Time These functions are accessed by calling metadata

    methods

  • 7/31/2019 JDBC Final

    25/55

    Function Types And Their UsesFunction

    Types Uses

    NumericFunctions

    Stringfunctions

    Time & Datefunctions

    Systemfunctions

    Conversion

    functions

    Operates on numeric data types such as greatest(),least(), length(),lower(),etc

    Operates on string data types such as char(), concat(),insert(), length(),etc.

    Access all the time and date related information fromdatabase.

    Retrieves the information about database managementsystem

    Convert data type of a given value into the required type

  • 7/31/2019 JDBC Final

    26/55

    Contd.

    In addition to these pre-definedfunctions,DBMS provides the feature tocreate user-defined functions that can be usedin DML queries.

    The user-defined functions can be used infollowing situations:

    In the column names of SELECT statement.

    As a condition in the WHERE clause. In the value clause of an INSERT statement.

    In the SET clause of an UPDATE statement.

  • 7/31/2019 JDBC Final

    27/55

    Contd The following is a syntax of how to create a user-

    defined function:

    Create [or replace] FUNCTION function-name[(parameter[, parameter])]RETURN return_datatypeIS/AS

    [Declaration_section]BEGINexecutable_section[Exception exception_section]

    END [function_name];

  • 7/31/2019 JDBC Final

    28/55

    Contd.

    The procedure to call a function in an application is

    same as it is in case of stored procedures.

    The syntax to invoke a function in JDBC is:

    {call ?:=function_name(?,?,..)} // with string parameters

    {call ?:=function_name} // with no parameter

  • 7/31/2019 JDBC Final

    29/55

    Using cursors in CallableStatement

    A cursor defines the runtime executionenvironment for a query where the result of the

    query execution can be captured.

    The syntax used to create a cursor is as follows:

    CREATE OR REPLACE PACKAGE package_name AS

    TYPE type_name IS REF CURSOR;

    END;

  • 7/31/2019 JDBC Final

    30/55

    Contd.

    The cursor is used to retrive the ResultSetfrom a database through CallableStatement.

    Following example shows the use of cursorsto get the ResultSet object to access multiple

    records from a database

  • 7/31/2019 JDBC Final

    31/55

    Example

    CREATE OR REPLACE PACKAGE mypack ASTYPE mycursor IS REF CURSOR;

    END;

    /

    Package created CREATE OR REPLACE FUNCTION getaccountdetails(actype NUMBER )

    RETURN mypack.mycursor AS

    myresult mypack.mycursor;

    BEGIN

    OPEN myresult FORSELECT accno, name, bal FROM account WHERE acctype = acc_type;

    RETURN myresult;

    END;

    /

    Function created

  • 7/31/2019 JDBC Final

    32/55

    Comparing procedure and Functions

    A function has areturn type.

    Functions can beused with SQL DMLqueries.

    A procedure issuitable to use DMLqueries .

    Procedures does not have returntype,rather if needed data can bemade available through OUTparameters.

    Procedures cannot be used withDML queries.

    A function is not suitable to useDML queries.

  • 7/31/2019 JDBC Final

    33/55

    ResultSet Interface

  • 7/31/2019 JDBC Final

    34/55

    ResultSet Interface ResultSet is an interface packaged in the java.sql

    package.

    The java.sql.ResultSet interface is defined todescribe an object, known as ResultSet object.

    It represents the data in tabular form that is

    retrieved by executing an SQL query. ResultSet object provides access to a pseudo

    table which is a result of a SQL query.

    ResultSet object holds zero or more objects.

  • 7/31/2019 JDBC Final

    35/55

    Maintain a cursor pointing to the current row ofdata.

    Initially the cursor is positioned before the firstrow.

    Moved ahead by the next() method.

    A default ResultSet object is not updatable andhas a cursor that moves forward only

    Obtain a ResultSet Object by usingexecuteQuery() or getResultSet() method.

  • 7/31/2019 JDBC Final

    36/55

    public ResultSet getResultSet() throwsSQLException

    Retrieves the current result as a ResultSet object. Thismethod should be called only once per result.

    Returns:

    the current result as a ResultSet object or null if

    the result is an update count or there are no moreresults

    Throws:

    SQLException - if a database access error occurs

  • 7/31/2019 JDBC Final

    37/55

    ResultSet follows iterate pattern.

    A single ResultSet object can be opened at a

    time.

    Obtain multiple ResultSets by using onestatement. When we try to open a ResultSet

    using a statement that is already associated withan opened ResultSet, the existing ResultSet isimplicitly closed.

  • 7/31/2019 JDBC Final

    38/55

    StatementObject

    st

    Java Application JDBC Driver

    J V M

    3) Compile & Executethe given SQL query

    4) Cache the result intobuffer (CURSOR)

    2

    67

    1

    rs

    5

    ResultSetObject

    next()boolean

    8

    9

    10

    11 getXXX()

    Buffer

    Result TableGet row

    DatafromDB buffer

    ResultSet Operation

  • 7/31/2019 JDBC Final

    39/55

    Methods of ResultSet

    absolute(int row)Moves the cursor to the given row number in this ResultSet

    object.

    afterLast()

    Moves the cursor to the end of this ResultSet object, just afterthe last row. beforeFirst()Moves the cursor to the front of this ResultSet object, just before

    the first row. close()Closes a ResultSet object and release all the JDBC resources

    connected to it. deleteRow()Deletes the specified row from a ResultSet object, as well as

    from the database.

  • 7/31/2019 JDBC Final

    40/55

    Methods of ResultSet

    first()

    Moves the cursor to the first row in a ResultSet object.

    getXXX()

    Retrieves the coloumn values of the specified typesfrom the current row. The type can be any of theJava predefined data types. Such as int, long, Byte,charcter, String, double etc.

    insertRow()Inserts the specified row and the contents into the

    ResultSet object as well as into the database.

  • 7/31/2019 JDBC Final

    41/55

    Methods of ResultSet

    next()Moves the cursor down one row from its current

    position. updateRow()Updates the underlying database with the new

    contents of the current row of this ResultSetobject.

    updateXXX()Updates the column values of the current row of

    the specified types.

  • 7/31/2019 JDBC Final

    42/55

    Data retrieving Steps

    1. Move the cursor position to the required rowInitially the cusor positioned before the first row. Use

    next() method of ResultSet to move the cursor position

    to the next record. It returns true if the new current rowis valid else false if there are no more rows.

    2. Reading the Column ValuesAfter moving the cursor to the respective row, use the

    getter methods (getXXX, getBoolean, getLong and so on)of ResultSet to retrieve the data from the row where thecursor is positioned.

  • 7/31/2019 JDBC Final

    43/55

    ResultSetMetaData Interface

  • 7/31/2019 JDBC Final

    44/55

    JDBC API provides the feature of MetaData thatcontains descriptive information about the data

    available in a database. JDBC MetaData providesinformation about tables, views,columnnames,column data types, stored procedures anddatabases.

    ResultSetMetaData interface offers informationabout the columns in a ResultSet, such as thecolumn name, column data type and length of thecolumn.

  • 7/31/2019 JDBC Final

    45/55

    Example:

    ResultSet rs = stmt.executeQuery("SELECT a, b,

    c FROM TABLE2");ResultSetMetaData rsmd = rs.getMetaData();

    int numberOfColumns = rsmd.getColumnCount();

    boolean b = rsmd.isSearchable(1);

  • 7/31/2019 JDBC Final

    46/55

    Methods of ResutSetMetaData getColumnCount()

    Returns the number of columns in this ResultSet

    object. getColumnName(int index)

    Takes the column index and returns the column name

    getColumnTypeName(int index)

    Takes the column index and returns the databasespecific type name.

    getSchemaName(int column)

    Get the designated column's table's schema.

  • 7/31/2019 JDBC Final

    47/55

    Methods of ResutSetMetaData getTableName(int column)

    Gets the designated column's table name.

    getColumnClassName(int column)

    Retrieves the java class name associated with theResultSet object.

    isReadOnly(int column)Indicates whether the designated column is

    definitely not writable.

  • 7/31/2019 JDBC Final

    48/55

    ResultSet Type(Package : java.sql.resultset) There Are 3 type :

    1. TYPE_FORWARD_ONLYCursor movement only forward

    2. TYPE_SCROLL_INSENSITIVECursor movement forward as well as backwardwithout reflecting changes

    3. TYPE_SCROLL_SENSITIVECursor movement forward as well as backwardwithout reflecting changes

  • 7/31/2019 JDBC Final

    49/55

    Methods to Navigate ResultSetMethod Use

    next() Move cursor toforwarddirection

    previous() Move cursor toBackwarddirection

    first() Moves cursor tofirstrow

    last() Moves cursor to lastrow

    relative(int rows) Moves relative to cursor positionwhere row values:0 indicate current position+ve int indicate forword move-ve int indicate backword move

    Absolute(int row_number) Moves cursor to given position

    beforeFirst() Moves cursor to beforefirst row

    afterLst() Moves cursor to after last row

    Note: 1. All methods return trueOR falseas the method affect the cursor position2. All method throws SQLExceptionexcept next()

  • 7/31/2019 JDBC Final

    50/55

    ResultSet Concurrency Used to determine functionality of resultSet

    Two type :

    1. CONCUR_READ_ONLY(Default)

    2. CONCUR_UPDATABLE

    To find the concurrency use :

    getConcurrency()To check the supportable by driver or not use :

    supportsResulrtSetConcurrency(int)where int : concurrency type

  • 7/31/2019 JDBC Final

    51/55

    Cursor Holdability Used to call Connection.commit()

    There are 2types :

    1. HOLD_CURSORS_OVER_COMMITHolds cursor when commit is called

    2. CLOSE_CURSORS_AT_COMMIT

    Cursor is closed when commit is called

  • 7/31/2019 JDBC Final

    52/55

    Manipulate data using ResultSet ObjectSteps1. Move cursor to the row where you need to

    update

    2. Use the ResultSet.UpdateXXX() methods tochange data (XXX-predefined data type)

    3. Invoke the UpdateRow() method of ResultSetobject to reflect changes into database(to verify commitment of update use methodrowUpdated())

    4. Closing connection usingResultSet.Close()

  • 7/31/2019 JDBC Final

    53/55

    DatabaseMetaData Interface(Package : java.sql.databasemetadata) Used to get information related to database and

    driver

    Used to create Generic Application To get the database details, such as vender

    name, product name, version

    To implement the advanced JDBC driver Syntax:

    DatabaseMetaData dbmd = Connection.getMetaData()

  • 7/31/2019 JDBC Final

    54/55

    Methods of DatabseMetaData interface

    Method Use

    int getDatabaseMajorVersion() Helps in retrieve major version ofdatabase in use

    int getDatabaseMinorVersion() Helps to retrieve minor version ofdatabase in use

    int getDatabaseProductVersion() Helps to retrieve product name ofdatabase in use

    int getDatabaseProductVersion() Helps to retrieve product version ofdatabase

    int getDriverName() Helps to retrieve driver name

    int getDriverVersion() Helps to retrieve driver version

    int getMaxConnections() Helps to retrieve max connection to thedatabase

  • 7/31/2019 JDBC Final

    55/55