Documente Academic
Documente Profesional
Documente Cultură
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
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
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);
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
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
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
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.
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
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.
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)
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
Method
Use
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
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()
int getDatabaseProductVersion()
int getDriverName() int getDriverVersion() int getMaxConnections()