Sunteți pe pagina 1din 55

PreparedStatement CallableStatement ResultSet Database MetaData

Package java.sql.PreparedStatement PreparedStatement(PS) Object is used to execute the parametrized SQL statement. PS object supports zero or more IN parameters. PS object represents a precompiled query that can be executed multiple times without compiling again and again.

PS object represent a pre-compiled SQL statement, so that the execution of the SQL statement is much faster as compared to the Statement object. java.sql.PreparedStatement is a subtype of the java.sql.Statement interface, therefore it inherits all the properties of the Statement interface.

Important Points about PS are as follows: A PreparedStatement object is associated with a Connection object. A PS object represent the execution plan of an SQL statement saved into the database that is passed as a parameter while creating the PS object. SQL statement can take parameters whose values can be set while operation. A PS is implicitly closed after the Connection object on which the PS object was created is closed.

JVM
Java Application JDBC Driver

3) Compile the given SQL Statement 4) Prepare an execution plan to execute the SQL statement 5) Store the execution plan with unique ID

con

1
8

Connection Object

7
11 setXXX() executeXXX() result Prepared Statemen t Object
14

ps

9
10
15

12) Locate the execution plan 13) Execute the plan with the given data

Steps involved in Using Prepared Statement

set methods of PreparedStatement


Return Type void
void void

Methods
setArray(int parameterIndex, Array x) Sets the designated parameter to the given java.sql.Array object. setBinaryStream(int parameterIndex, InputStream x) Sets the designated parameter to the given input stream. setBinaryStream(int parameterIndex, InputStream x, int length) Sets the designated parameter to the given input stream, which will have the specified number of bytes. setBoolean(int parameterIndex, boolean x) Sets the designated parameter to the given Java boolean value. setDate(int parameterIndex, Date x) setDouble(int parameterIndex, double x) setFloat(int parameterIndex, float x) setInt(int parameterIndex, int x)

void
void void void void

void void
void

setLong(int parameterIndex, long x) setObject(int parameterIndex, Object x)


setString(int parameterIndex, String x)

Advantages: It improves the performance of application, where same query is to be executed no. of times. It is easier to insert or update the SQL 99 data type columns, such as BLOB, CLOB, or OBJECT It provides a programmatic approach to set the values of parameters in a more descriptive way.

Disadvantages:
It can represent only one SQL statement. Therefore, we cannot execute more than one statement by a single PreparedStatement. It supports to add only a single SQL statement to be executed for multiple times with different set of values it a batch.

Broad level steps to use PreparedStatement: 1. Create a PreparedStatement object 2. Set the values for the Parameters 3. Execute the PreparedStatement Creating a PreparedStatement object Created by using the prepareStatement(String sqlStatement) method of the Connection object. Connection object submits the SQL statement, and database returns an identity of the execution plan prepared for the SQL statement, if compilation was successful. prepareStatement(String) method can contain a zero or more question marks(?, known as prameters

Values can be set for? after the SQL statement is compiled, i.e. after creating PS object or before executing 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 the Connection object.

Setting the Values for Parameters:


The PS object supports setter methods for all the data types supported by Java.
It accepts two argument. First, indicate parameter 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, from left to right of the statement.

Executing the PreparedStatement: After preparing and initializing the PS object, we can execute the SQL statement with the configured parameter. execute() returns boolean, executeUpdate() return int, executeQuery() returns ResultSet methods of the PS object are used to execute the SQL statement.

int n = ps.executeUpdate();
//n holds the no. of rows or tables that re being update.

Callable statement

In java callable statement is used to call the stored procedures and functions. That is the procedure can be called by using an object of the callablestatement interface. They are use ti access,invoke, and retrive the results of sql stored procedures,functions and cursors.

Procedures

Ussing callablestatement

Calling Functions By Using CallableStatement


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

Function Types And Their Uses


Function Types

Uses

Numeric Functions String functions Time & Date functions System functions 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 from database. Retrieves the information about database management system Convert data type of a given value into the required type

Contd.
In addition to these pre-defined functions,DBMS provides the feature to create user-defined functions that can be used in DML queries. The user-defined functions can be used in following 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.

Contd
The following is a syntax of how to create a userdefined function:
Create [or replace] FUNCTION function-name [(parameter[, parameter])] RETURN return_datatype IS/AS [Declaration_section] BEGIN executable_section [Exception exception_section] END [function_name];

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

Using cursors in CallableStatement


A cursor defines the runtime execution environment 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;

Contd.
The cursor is used to retrive the ResultSet from a database through CallableStatement. Following example shows the use of cursors to get the ResultSet object to access multiple records from a database

Example

CREATE OR REPLACE PACKAGE mypack AS TYPE mycursor IS REF CURSOR; END; / Package created

CREATE OR REPLACE FUNCTION getaccountdetails(actype NUMBER ) RETURN mypack.mycursor AS myresult mypack.mycursor; BEGIN OPEN myresult FOR SELECT accno, name, bal FROM account WHERE acctype = acc_type; RETURN myresult; END; / Function created

Comparing procedure and Functions


A function has a return type. Procedures does not have return type,rather if needed data can be made available through OUT parameters. Procedures cannot be used with DML queries. A function is not suitable to use DML queries.

Functions can be used with SQL DML queries. A procedure is suitable to use DML queries .

ResultSet Interface

ResultSet Interface
ResultSet is an interface packaged in the java.sql package. The java.sql.ResultSet interface is defined to describe 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.

Maintain a cursor pointing to the current row of data. Initially the cursor is positioned before the first row. Moved ahead by the next() method. A default ResultSet object is not updatable and has a cursor that moves forward only Obtain a ResultSet Object by using executeQuery() or getResultSet() method.

public ResultSet getResultSet() throws SQLException Retrieves the current result as a ResultSet object. This method 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 more results Throws: SQLException - if a database access error occurs

ResultSet follows iterate pattern. A single ResultSet object can be opened at a time. Obtain multiple ResultSets by using one statement. When we try to open a ResultSet using a statement that is already associated with an opened ResultSet, the existing ResultSet is implicitly closed.

JVM Java Application JDBC Driver

2 5

3) Compile & Execute the given SQL query 4) Cache the result into buffer (CURSOR)

st 1
Statement Object

6
Buffer
Get row Datafrom DB buffer

rs

8
10 11

Result

Table

next() boolean getXXX() ResultSet Object

ResultSet Operation

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 after the 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.

Methods of ResultSet
first() Moves the cursor to the first row in a ResultSet object. getXXX() Retrieves the coloumn values of the specified types from the current row. The type can be any of the Java 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.

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 ResultSet object. updateXXX() Updates the column values of the current row of the specified types.

Data retrieving Steps


1. Move the cursor position to the required row Initially 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 row is valid else false if there are no more rows.
2. Reading the Column Values After 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 the cursor is positioned.

ResultSetMetaData Interface

JDBC API provides the feature of MetaData that contains descriptive information about the data available in a database. JDBC MetaData provides information about tables, views,column names,column data types, stored procedures and databases.

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

Example: ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); boolean b = rsmd.isSearchable(1);

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 database specific type name. getSchemaName(int column) Get the designated column's table's schema.

Methods of ResutSetMetaData
getTableName(int column) Gets the designated column's table name. getColumnClassName(int column) Retrieves the java class name associated with the ResultSet object. isReadOnly(int column) Indicates whether the designated column is definitely not writable.

ResultSet Type
(Package : java.sql.resultset)

There Are 3 type : 1. TYPE_FORWARD_ONLY


Cursor movement only forward

2. TYPE_SCROLL_INSENSITIVE
Cursor movement forward as well as backward without reflecting changes

3. TYPE_SCROLL_SENSITIVE
Cursor movement forward as well as backward without reflecting changes

Methods to Navigate cursor to forward direction next() Move ResultSet


previous()
first() last() relative(int rows)

Method

Use

Move cursor to Backward direction


Moves cursor to first row Moves cursor to last row Moves relative to cursor position where row values: 0 indicate current position +ve int indicate forword move -ve int indicate backword move Moves cursor to given position Moves cursor to before first row Moves cursor to after last row

Absolute(int row_number) beforeFirst() afterLst()

Note: 1. All methods return true OR false as the method affect the cursor position 2. All method throws SQLException except next()

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

Cursor Holdability
Used to call Connection.commit() There are 2types :
1. HOLD_CURSORS_OVER_COMMIT
Holds cursor when commit is called

2. CLOSE_CURSORS_AT_COMMIT
Cursor is closed when commit is called

Manipulate data using ResultSet Object


Steps 1. Move cursor to the row where you need to update 2. Use the ResultSet.UpdateXXX() methods to change data (XXX-predefined data type) 3. Invoke the UpdateRow() method of ResultSet object to reflect changes into database

(to verify commitment of update use method rowUpdated())

4. Closing connection using ResultSet.Close()

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

Methods of DatabseMetaData interface


Method int getDatabaseMajorVersion() int getDatabaseMinorVersion() int getDatabaseProductVersion() Use Helps in retrieve major version of database in use Helps to retrieve minor version of database in use Helps to retrieve product name of database in use

int getDatabaseProductVersion()
int getDriverName() int getDriverVersion() int getMaxConnections()

Helps to retrieve product version of database


Helps to retrieve driver name Helps to retrieve driver version Helps to retrieve max connection to the database

S-ar putea să vă placă și