SlideShare a Scribd company logo
UNIT 4 part 1
Database Connectivity
JAVA
Muhammed Mashahil P
❏ JDBC is Java application programming interface that allows the Java
programmers to access database management system from the java
code.
❏ It was developed by JavaSoft, a subsidiary of Sun Microsystems.
❏ It is a java API which enables the java programs to execute SQL
statements
❏ JDBC provides methods for querying and updating the data in Relational
Database Management system such as SQL, Oracle etc.
❏ Generally all Relational Database Management System supports SQL
and we all know that Java is platform independent.
❏ So JDBC makes it possible to write a single database application that
can run on different platforms and interact with different Database
Management Systems.
JDBC?
❏ JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database.
❏ It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.
JDBC?
ODBC (Open Data Base Connectivity)
❏ Open DataBase Connectivity is similar to Java Database Connectivity which
is used for accessing and managing database,
❏ but the difference is that JDBC is designed specifically for Java programs,
whereas ODBC is not depended upon any language
The JDBC-ODBC bridge
❏ The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database
driver that utilize the ODBC driver to connect the database.
❏ This driver translates JDBC method calls into ODBC function calls.
❏ The Bridge implements Jdbc for any database for which an Odbc driver is
available.
❏ The Bridge is always implemented as the sun.jdbc.odbc Java package and it
contains a native library used to access ODBC.
❏ There are four types of JDBC drivers:
❏ JDBC-ODBC Bridge Driver,
❏ Native Driver,
❏ Network Protocol Driver, and
❏ Thin Driver
1) JDBC-ODBC bridge driver
❏ The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls.
❏ This is now discouraged because of thin driver.
❏ Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
❏ Advantages:
❏ easy to use.
❏ can be easily connected to any database.
❏ Disadvantages:
❏ Performance degraded because JDBC method call is
converted into the ODBC function calls.
❏ The ODBC driver needs to be installed on the client
machine.
2) Native-API driver
❏ The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java..
Advantages:
❏ performance upgraded than JDBC-ODBC bridge driver.
Disadvantages:
❏ The Native driver needs to be installed on the each client machine.
❏ The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
❏ The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantages:
#No client side library is required because of application server that can perform many tasks like auditing,
load balancing, logging etc.
Disadvantages:
#Network support is required on client machine.
#Requires database-specific coding to be done in the middle tier.
#Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier.
4) Thin driver
❏ The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantages:
#Better performance than all other drivers.
#No software is required at client side or server side.
Disadvantages:
#Drivers depend on the Database
JDBC
❏ The JDBC API supports both two-tier and three-tier models for database
access.
❏ Two-tier model -- a Java applet or application interacts directly with the
database.
❏ Three-tier model -- introduces a middle-level server for execution of
business logic:
❏ the middle tier to maintain control over data access.
❏ the user can employ an easy-to-use higher-level API which is translated by
the middle tier into the appropriate low-level calls.
JDBC architecture
JDBC API
❏ The JDBC API provides the facility for accessing the relational database from the
Java programming language.
❏ The user not only execute the SQL statements, retrieve results, and update the
data but can also access it anywhere within a network because of it's "Write Once,
Run Anywhere" (WORA) capabilities.
❏ Due to JDBC API technology, user can also access other tabular data sources
like spreadsheets or flat files even in the a heterogeneous environment.
❏ JDBC application programming interface is a part of the Java platform that have
included Java SE and Java EE in itself.
❏ The latest version of JDBC 4.0 application programming interface is divided into
two packages.
i) java.sql.
ii) javax.sql.
❏ Java SE and Java EE platforms are included in both the packages.
JDBC Driver Manager
❏ The JDBC Driver Manager is a very important class that defines objects
which connect Java applications to a JDBC driver.
❏ Usually Driver Manager is the backbone of the JDBC architecture.
❏ It's very simple and small that is used to provide a means of managing the
different types of JDBC database driver running on an application
❏ The main responsibility of JDBC database driver is to load all the drivers
found in the system properly as well as to select the most appropriate driver
from opening a connection to a database.
❏ The Driver Manager also helps to select the most appropriate driver from the
previously loaded drivers when a new open database is connected.
JDBC Driver Manager (contn)
❏ The function of JDBC driver test suite is to make ensure that the JDBC
drivers will run user's program or not .
❏ The test suite of JDBC application program interface is very useful for testing
a driver based on JDBC technology during testing period.
❏ It ensures the requirement of Java Platform Enterprise Edition (J2EE).
Database
A Database is a collection of related data organised in a way that data can be easily
accessed, managed and updated. Database can be software based or hardware based, with
one sole purpose, storing data.
DBMS
A DBMS is a software that allows creation, definition and manipulation of database, allowing
users to store, process and analyse data easily. DBMS provides us with an interface or a
tool, to perform various operations like creating database, storing data in it, updating data,
creating tables in the database and a lot more.
DBMS also provides protection and security to the databases. It also maintains data
consistency in case of multiple users.
Here are some examples of popular DBMS used these days:
- MySql
- Oracle
- SQL Server
- IBM DB2
SQL Package
❏ Provides the API for accessing and processing data stored in a data source
(usually a relational database) using the Java programming language.
❏ This API includes a framework whereby different drivers can be installed
dynamically to access different data sources.
❏ Although the JDBCTM API is mainly geared to passing SQL statements to a
database, it provides for reading and writing data from any data source with a
tabular format.
❏ The reader/writer facility, available through the javax.sql.RowSet group of
interfaces, can be customized to use and update data from a spread sheet, or
any other tabular data source
CONTENTS OF SQL PACKAGE
❏ The java.sql package contains API for the following:
1. Making a connection with a database via the DriverManager facility
CONTENTS OF SQL PACKAGE
2. Sending SQL statements to a database
3. Retrieving and updating the results of a query
- ResultSet interface Class or Interface
CONTENTS OF SQL PACKAGE
4. Standard mappings for SQL types to classes and interfaces in the Java
programming language
CONTENTS OF SQL PACKAGE
5. Custom mapping an SQL user-defined type (UDT) to a class in the Java
6. Metadata
CONTENTS OF SQL PACKAGE
7.Exceptions
Data types
DriverManager Class
Following are the methods of DriverManager class:
1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers
registered in the DriverManager class.
2. registerDriver(Driver driver) :It registers the driver with the DriverManager class.
3. getConnection(String url) : It tries to establish the connection to a given
database URL.
4. getConnection(String url, String user, String password) : It tries to establish
the connection to a given database URL.
5. getConnection(String url, Properties info) : It tries to establish the connection
to a given database URL.
6. getDriver(String url) : It attempts to locate the driver by the given string.
7. getDrivers() : It retrieves the enumeration of the drivers which has been
registered with the DriverManager class.
SEVEN BASIC STEPS IN ESTABLISHING CONNECTION WITH DATABASE
1. Import package
2. Load and register the driver.
3. Establish the Connection.
4. Create a Statement object.
5. Execute a Query.
6. Process the results.
7. Close the connection.
STEP 1-Import package
- java.sql:
Provides the API for accessing and processing data stored in a data source
(usually a relational database) using the JavaTM programming language.This API
includes a framework whereby different drivers can be installed dynamically to
access different data sources. Although the JDBCTM API is mainly geared to
passing SQL statements to a database, it provides for reading and writing data
from any data source with a tabular format.
- javax.sql:
Provides the API for server side data source access and processing from the
JavaTM programming language. This package supplements the java.sql package
and, as of the version 1.4 release, is included in the Java Platform, Standard
Edition (Java SETM). It remains an essential part of the Java Platform, Enterprise
Edition (Java EETM).The reader/writer facility, available through the
javax.sql.RowSet group of interfaces, can be customized to use and update data
from a spread sheet, flat file, or any other tabular data source
STEP 2-Load and register the driver
A. Load Driver
- Which driver loads based on which database we are going to connecting with
Eg:- For mysql
com.mysql.jdbc.Driver
- To load the driver we have to Download it
Eg:- For mysql
Mysql connector from mysql website
A. Register Driver
- To register we have to use method forName()
Eg:-
Syntax of Class.forName() method:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
For mysql
class.forName(“com.mysql.jdbc.Driver”);
STEP 3-Establish connection
- After registering and loading the driver,
- we will create a connection using getConnection() method of DriverManager class.
- This method has several overloaded methods that can be used based on the requirement.
- Basically it require the database name, username and password to establish connection.
Syntax
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
For Example:-
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:XE","usrnme", "password");
STEP 4- Create SQL Statement
❏ You need to create a Statement object to send requests to and retrieve
results from a database.
❏ The Connection object provides the createStatement () method to create a
Statement object.
❏ It is used to execute the sql queries and defined in Connection class.
Syntax of the method is given below.
public Statement createStatement() throws SQLException
Example to create a SQL statement
Statement s=con.createStatement();
STEP 5- Execute SQL Statement
❏ After creating statement, now execute using executeQuery() method of
Statement interface.
❏ This method is used to execute SQL statements. Syntax of the method is
given below.
Syntax of the method is given below.
public ResultSet executeQuery(String query) throws SQLException
Example to create a SQL statement
ResultSet rs=s.executeQuery("select * from user");
STEP 6- Process the results.
❏ Process the Result In this step we receives the result of execute statement. In
this case we will fetch the student records from the recordset object and show
on the command prompt.
Here is the code:
// 1 2
//rollno name
Example to create a SQL statement
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
//System.out.println(rs.getInt(“Rollno”)+" "+rs.getString(2));
}
Rollno Name
Student
STEP 7- Closing the connection
❏ This is final step which includes closing all the connection that we opened in
our previous steps.
❏ After executing SQL statement you need to close the connection and release
the session.
❏ The close() method of Connection interface is used to close the connection.
Syntax of the method is given below.
public void close() throws SQLException
Example to create a SQL statement
con.close();
Example
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
//Loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//creating connection
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"usrname", "pssword");
Statement s = con.createStatement(); //creating statement
ResultSet rs = s.executeQuery("select * from Student"); //executing statement
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close(); //closing connection
} catch (Exception e) {
e.printStacktrace();
} } }
ResultSet Interface
- The object of ResultSet maintains a cursor pointing to a row of a table.
- Initially, cursor points to before the first row.
- By default, ResultSet object can be moved forward only and it is not updatable.
- But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the result set is not sensitive to
changes made by others to the database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result set is sensitive to
changes made by others to the database that occur after the result set was created.
ResultSet Interface - Methods
Type Description
1) public boolean next(): is used to move the cursor to the one row next from the current position.
2) public boolean previous(): is used to move the cursor to the one row previous from the current position.
3) public boolean first():
is used to move the cursor to the first row in result set object.
4) public boolean last():
is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row):
is used to move the cursor to the specified row number in the ResultSet object.
6) public boolean relative(int row):
is used to move the cursor to the relative row number in the ResultSet object, it
may be positive or negative.
7) public int getInt(int columnIndex):
is used to return the data of specified column index of the current row as int.
8) public int getInt(String columnName):
is used to return the data of specified column name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.
10) public String getString(String
columnName):
is used to return the data of specified column name of the current row as String.
Example
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from employee");
//getting the record of 4th row
rs.absolute(4);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}}
the simple example of ResultSet interface to retrieve the data of 4th row.
SQL Insert ,Create, Update and Delete
String str = “INSERT INTO authors (au_id, au_lname) VALUES (‘998’,’ABC’)” ;
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
String str = “DELETE FROM authors WHERE lname=‘ABC’ ” ;
String str = “CREATE TABLE MyProduct” + “ (p_id INTEGER, ” + ”p_name
VARCHAR(25), ” + “rate FLOAT ,” + “unit_msr CHAR (6) )” ;
Handling SQL Exceptions
❏ The java.sql package provides the SQLException class , which is derived from the
java.lang.Exception class.
❏ The SQLException is thrown by various methods in the JDBC API and enables
you to determine the reason of the errors that occur while connecting a Java
application to a database.
❏ You can catch the SQLException in a Java application using the try and catch
exception handling block.
❏ The methods in the SQLException class are :
- int getErrorCode () : Returns the error code associated with the error occurred.
- String getSQLState() : X/Open error code.
- SQLException getNextException () : Returns the next exceptions in the chain of
exceptions.
Handling SQL Exceptions -Example
try {
String str = “DELETE FROM authors WHERE au_id = ‘123’ ” ;
Statement stmt = con.createStatement();
int count = stmt.executeUpdate (str) ;
}
catch (SQLException sqlexception)
{
System.out.println (“Display Error Code”) ;
System.out.println( “SQL Exception” + sqlexception.getErrorCode ()) ;
}
Example
import java.sql.*;
public class JDBCStmt {
public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver"); // Loading driver
// Creating connection
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", "root", "admin")
Statement stmt = con.createStatement(); // creating Statement
boolean flag = stmt.execute("Update Employee set age = 40 where id in (5, 6)");
/** execute method **/
if(flag == false){
System.out.println("Updated rows " + stmt.getUpdateCount() ); }
/** executeUpdate method **/
int count = stmt.executeUpdate("Insert into employee(name, age) values('Kim', 23)"); //
Insert
System.out.println("Rows Inserted " + count);
count = stmt.executeUpdate("Update Employee set age = 35 where id = 17"); //
update
System.out.println("Rows Updated " + count);
/** executeQuery method **/
ResultSet rs = stmt.executeQuery("Select * from Employee"); // Executing Query
while(rs.next()){ // Processing Resultset
System.out.println("id : " + rs.getInt("id") + " Name : " + rs.getString("name") + " Age : " + rs.getInt("age"));
}
} catch (ClassNotFoundException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) { // TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){ //closing connection
try {
connection.close();
} catch (SQLException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
} // if condition
} // finally
}
}
Example
Statement interface
❏ Statement interface resides in java.sql package and it is used to execute a static
SQL statement and returning the result of the executed query.
❏ Statement interface has two sub-interfaces CallableStatement and
PreparedStatement.
❏ get a Statement object by calling the Connection.createStatement() method on
the Connection object.
Statement interface Methods
The Statement interface provides various methods
1. boolean execute(String sql) : Executes the given SQL statement (it can be any kind
of SQL query), which may return multiple results.
Returns a boolean which is true if the first result is a ResultSet object; false if it is an
update count or there are no results.
2. ResultSet executeQuery(String sql): Executes the given SQL statement, which
returns a single ResultSet object. If you want to execute a Select SQL query which returns
results you should use this method.
3. int executeUpdate(String sql): Executes the given SQL statement, which may be an
INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as
an SQL DDL statement.Returns an int denoting either the row count for the rows that are
inserted, deleted, updated or returns 0 if nothing is returned.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
4. int[] executeBatch(): Submits a batch of commands to the database for execution
and if all commands execute successfully, returns an array of update counts.
PreparedStatement interface
❏ The PreparedStatement objects accepts the runtime parameters.
❏ The PreparedStatement interface is derived from the Statement interface and is
available in the java.sql package.
❏ The PreparedStatement objects are compiled and prepared only once by JDBC.
The future invocation of the PreparedStatement object does not recompile the
SQL statements.
❏ This helps in reducing the load on the database server and thus improving the
performance of the application .
PreparedStatement interface
❏ The PreparedStatement interface inherits the following methods to execute SQL
statement s 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.
PreparedStatement interface
stat = con.prepareStatement(“SELECT * FROM authors WHERE au_id = ? ”) ;
The SQL statement can contain ‘ ? ‘ symbol as placeholder that can be replaced
by input parameters at runtime.
Before executing the SQL statements specified in the PreparedStatement object ,
you must set the value of each ‘ ? ‘ parameter.
This is done by calling an appropriate setXXX () method , where XXX is the data
type of the parameter.
stat.setString (1, “123”);
ResultSet rs = stat.executeQuery ();
PreparedStatement interface Methods
The PreparedStatement interface provides various methods to set the value of the
placeholders for the specific data types.
1. void setByte (int index , byte val) : Sets the java byte type value for the
parameter corresponding to index passed as a parameter.
2. void setBytes (int index , byte[] val) : Sets the Java byte type array for the
parameter corresponding to index passed as a parameter.
3. void setBoolean (int index , boolean val) : Sets the Java boolean type value for
the parameter corresponding to index passed as a parameter.
4. void setDouble (int index, double val) : Sets the Java double type value value
for the parameter corresponding to the index passed as a parameter.
PreparedStatement interface Methods
5. void setInt (int index , int val) : Sets the Java int type value for the parameter
corresponding to index passed as a parameter.
6. void setLong(int index , long val) : Sets the Java long type value for the
parameter corresponding to index passed as a parameter.
7. void setFloat (int index , float val) : Sets the Java float type value for the
parameter corresponding to index passed as a parameter.
8. void setShort (int index , short val) : Sets the Java short type value for the
parameter corresponding to index passed as a parameter.
9. void setString(int index , String val) : Sets the Java String type value for the
parameter corresponding to index passed as a parameter.
Retrieving Rows
String str = “SELECT * FROM titles WHERE au_id = ? ” ;
PreparedStatement ps = con.prepareStatement(str) ;
ps.setString(1 , “101”);
ResultSet rs = ps.executeQuery ();
Inserting Rows
String str = “ INSERT INTO authors (au_id , au_fname , au_lname) VALUES (? , ? , ? ) ” ;
ps = con.prepareStatement(str);
ps.setString (1, “101”);
ps.setString (2, “ABC”);
ps.setString (3 , “XYZ”);
int rt = ps.executeUpdate() ;
Updating & Deleting Row
String str = “ UPDATE authors SET state = ? WHERE city = ? “ ;
PreparedStatement ps = con.prepareStatement(str);
ps.setString (1, “MH”);
ps.setString (2, “Pune”);
int rt = ps.executeUpdate() ;
String str = “ DELETE FROM authors WHERE au_fname = ? “ ;
PreparedStatement ps = con.prepareStatement(str);
ps.setString (1, “PPPP”);
int rt = ps.executeUpdate() ;
Creating Stored Procedures
❏ You can use the executeUpdate () to execute the CREATE PROCEDURE SQL statement.
❏ Stored procedures can be of two types , parameterized and non- parameterized. Non –
parameterized stored procedure in a JDBC application:
❏ When you use the stored procedures to perform database operations, it reduces network
traffic because instead of sending multiple SQL statements to a database , a single stored
procedure is executed.
String str = “ CREATE PROCEDURE authors_info” + “AS” + “SELECT au_id ,
au_lname , au_fname” + ”FROM authors” + “WHERE city = ‘Pune’ ” + ”ORDER
BY au_fname” ;
Statement stmt = con.createStatement () ;
int rt = stmt.executeUpdate (str);
The Connection object con is used to send the CREATE PROCEDURE SQL statement to a
database. When you execute the code , the authors_info stored procedure is created and
stored in the database.
Creating Stored Procedures
You can use the following code snippet to create a parameterized stored procedure.
String str = “ CREATE PROCEDURE authors_info_prmtz @auth_id varchar(15) ,
@auth_fname varchar(20) output , @auth_lname varchar(20) output , @auth_city
varchar(20) output , @auth_state varchar(20) output ” + “AS”
+ “SELECT @auth_fname = au_fname , @auth_lname = au_lname , @auth_city = city
, @auth_state = state ” + “ FROM authors ” + “ WHERE au_id = @auth_id ” ;
Statement stmt = con.createStatement () ;
int rt = stmt.executeUpdate (str);
Creating Stored Procedures
- In the preceding code snippet , the authors_info_prmtz stored procedure is
created that accepts author id as parameter and retrieve the corresponding author
information form the database.
- The retrieved information is stored in the OUT parameter. The SQL Server 2000
uses output keyword to represent OUT parameters.
- A stored procedure can accepts one or multiple parameters.
- A parameter of a stored procedure can take any of these forms :
1. IN : Refers to the argument that you pass to a stored procedure.
2. OUT : Refers to the return value of a stored procedure.
3. 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
Calling a Stored Procedure without Parameters
- The Connection interface provides the prepareCall() method that is used to create the
CallableStatement object .
- This object is used to a call a stored procedure of a database .
- The prepareCall () is an overloaded method that has the following 3 forms:
1. CallableStatement prepareCall (String str) : Creates a CallableStatement object to call a stored
procedure. The prepareCall () accepts a string as a parameter that contains an SQL statement to call
a stored procedure. You can also specify the placeholders to accept parameters in the SQL
statement.
2. CallableStatement prepareCall(String str , int resSetType , int resSetConc): Creates a
CallableStatement object that returns ResultSet object that has the specified result set type and
concurrency mode. The method accepts following 3 parameter :
String object :Contains the SQL statement to call a stored procedure. The SQL statement can
contains one or more parameters.
ResultSet types : Specifies any of the 3 result set types , TYPE_FORWARD_ONLY ,
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE.
ResultSet concurrency modes :Specifies either of these concurrency modes ,
CONCUR_READ_ONLY or CONCUR_UPDATABLE , for a result set
Calling a Stored Procedure without Parameters
3. CallableStatement prepareCall (String str , int resSetType , int resSetConcur , int
resSetHoldability) : Creates a CallableStatement object that returns a ResultSet object . This
ResultSet object has the specified result type, concurrency mode, and constant to set the result set
state.
The syntax to call a stored procedure without parameter is : { call <procedure_name> } ;
Eg:
String str = “ {call authors_info}” ;
CallableStatement cs = con.prepareCall (str) ;
ResultSet rs = cs.executeQuery() ;
while(rs.next()) {
System.out.println(“Author ID :” + rs.getString(1) + “t”);
System.out.println(“Author First Name :” + rs.getString(2) + “t”);
System.out.println(“Author Last Name :” + rs.getString(3) + “t”);
}
Calling a Stored Procedure with Parameters
- The SQL escape syntax is used to call a stored procedure with parameters.
- There are two forms of the SQL escape syntax, one that contains result parameter and one
that does not.
- If the SQL escape syntax contains a result parameter, the result parameter is used to return
a value from a stored procedure.
- The result parameter is an OUT parameter. Other parameters of the SQL escape syntax can
contain IN , OUT , or INOUT parameters.
- The syntax to call a stored procedure with parameter is :
{ call <procedure_name> (?)} ;
- You need to set the value of the IN parameters before the CallableStatement object
executed , otherwise the SQLException is thrown while processing the stored procedure.
<CallableStatement_object>.setInt(<value>)
Calling a Stored Procedure with Parameters
- If the stored procedure contains OUT and INOUT parameters, these parameters should be
registered with corresponding JDBC types before a call to a stored procedures is processed.
- The JDBC types determine the Java data types that are used in the get methods while
retrieving the values of the OUT and INOUT parameters.
cs.registerOutParameter (1 . Java.sql.Types.STRING) ;
Accepts the position of the placeholder and a constant in the java.sql.Types class as
parameters.
cs.registerOutParameter (1, java.sql.Types.DECIMAL , 3) ;
What for 3rd Parameter used for ?
Calling a Stored Procedure with Parameters
import java.sql.*;
public class CallProc { public static void main(String arg []) {
String id , fname , lname , address , city ;
try { String str = “ { call authors_info ( ? , ? , ? , ? , ? ) } ” ;
Class.forname (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:DSN”) ;
CallableStatement cs = con.prepareCall (str) ;
cs.setString (1 , “123-456” ) ; // pass IN parameter
//Register OUT paramter
cs.registerOutParameter(2 , Types.VARCHAR);
cs.registerOutParameter(3 , Types.VARCHAR);
cs.registerOutParameter(4 , Types.VARCHAR);
cs.registerOutParameter(5 , Types.VARCHAR);
// process the Stored procedure
cs.execute () ;
fname = cs.getString(2) ;
lname = cs.getString(3) ;
address = cs.getString(4) ;
city = cs.getString(5) ;
-----
---- }}
ResultSetMetaData
- The ResultSetMetaData interface contains various methods that enable you to retrieve
information about the data in a result set , such as number of columns , names of columns and
data types of the columns.
- The ResultSet interface provides the getMetaData () method to create an object of the
ResultSetMetaData interface .
ResultSetMetaData rm = rs.getMetaData() ;
The following lists the commonly used methods of the ResultSetMetaData interface :
- int getColumnCount () : Returns an integer indicating the total number of columns in a ResultSet
object .
- String getColumnLabel (int col_index) : Retrieves the title of the table column corresponding to
the index passed as a parameter to this method.
- String getColumnName (int col_index) : Retrieves the name of the table column corresponding to
the index passed as a parameter to this method.
- int getColumnType (int col_index) : Retrieves the SQL data type of the table column
corresponding to the index passed as a parameter.
ResultMetaData
- String getTableName(int col_index) : Retrieves the name of the database table that contains the
column corresponding to the index passed as a parameter.
- boolean isAutoIncrement (int col_index) : Returns a boolean value that indicates whether the
table column corresponding to the index passed as a parameter increments automatically.
- boolean isCaseSensitive (int col_index) : Returns a boolean value that indicates whether the
table column corresponding to the index passed as a parameter is case sensitive.
- boolean isReadOnly (int col_index) : Returns a boolean value that indicates whether the column
in a ResultSet corresponding to the index passed as a parameter is read only.
- boolean isWritable (int col_index) : Returns a boolean value that indicates whether ResultSet
column corresponding to the index passed as a parameter is updatable.
END

More Related Content

Similar to java 4 Part 1 computer science.pptx

Jdbc
JdbcJdbc
Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)
Gera Paulos
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
Jdbc
JdbcJdbc
jdbc
jdbcjdbc
jdbc
shreeuva
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
Sourabrata Mukherjee
 
JDBC
JDBCJDBC
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
Jafar Nesargi
 
jdbc document
jdbc documentjdbc document
jdbc document
Yamuna Devi
 
jdbc
jdbcjdbc
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
Jdbc
JdbcJdbc
Jdbc
gee eew3
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
Hemo Chella
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
kingkolju
 
Jdbc
JdbcJdbc

Similar to java 4 Part 1 computer science.pptx (20)

Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc
jdbcjdbc
jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
JDBC
JDBCJDBC
JDBC
 
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
 
jdbc document
jdbc documentjdbc document
jdbc document
 
jdbc
jdbcjdbc
jdbc
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
Jdbc
JdbcJdbc
Jdbc
 

More from MUHAMMED MASHAHIL PUKKUNNUMMAL

IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
flow of control python.pdf
flow of control python.pdfflow of control python.pdf
flow of control python.pdf
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Database Management using MS Access.pdf
Database Management using MS Access.pdfDatabase Management using MS Access.pdf
Database Management using MS Access.pdf
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
CA-Web Hosting-Slide.pptx
CA-Web Hosting-Slide.pptxCA-Web Hosting-Slide.pptx
CA-Web Hosting-Slide.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
loops python.pdf
loops python.pdfloops python.pdf
flow of control python.pdf
flow of control python.pdfflow of control python.pdf
flow of control python.pdf
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Java 2 computer science.pptx
Java 2 computer science.pptxJava 2 computer science.pptx
Java 2 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
java part 1 computer science.pptx
java part 1 computer science.pptxjava part 1 computer science.pptx
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
2-Arrays.pdf
2-Arrays.pdf2-Arrays.pdf
Variable scope in php
Variable scope in phpVariable scope in php
Variable scope in php
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Vardump and printr in php
Vardump and printr in phpVardump and printr in php
Vardump and printr in php
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Unit1 DBMS Introduction
Unit1 DBMS IntroductionUnit1 DBMS Introduction
Unit1 DBMS Introduction
MUHAMMED MASHAHIL PUKKUNNUMMAL
 

More from MUHAMMED MASHAHIL PUKKUNNUMMAL (14)

IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
flow of control python.pdf
flow of control python.pdfflow of control python.pdf
flow of control python.pdf
 
Database Management using MS Access.pdf
Database Management using MS Access.pdfDatabase Management using MS Access.pdf
Database Management using MS Access.pdf
 
CA-Web Hosting-Slide.pptx
CA-Web Hosting-Slide.pptxCA-Web Hosting-Slide.pptx
CA-Web Hosting-Slide.pptx
 
loops python.pdf
loops python.pdfloops python.pdf
loops python.pdf
 
flow of control python.pdf
flow of control python.pdfflow of control python.pdf
flow of control python.pdf
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
Java 2 computer science.pptx
Java 2 computer science.pptxJava 2 computer science.pptx
Java 2 computer science.pptx
 
java part 1 computer science.pptx
java part 1 computer science.pptxjava part 1 computer science.pptx
java part 1 computer science.pptx
 
2-Arrays.pdf
2-Arrays.pdf2-Arrays.pdf
2-Arrays.pdf
 
Variable scope in php
Variable scope in phpVariable scope in php
Variable scope in php
 
Vardump and printr in php
Vardump and printr in phpVardump and printr in php
Vardump and printr in php
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
Unit1 DBMS Introduction
Unit1 DBMS IntroductionUnit1 DBMS Introduction
Unit1 DBMS Introduction
 

Recently uploaded

Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
ycwu0509
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
CVCSOfficial
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 

Recently uploaded (20)

Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 

java 4 Part 1 computer science.pptx

  • 1. UNIT 4 part 1 Database Connectivity JAVA Muhammed Mashahil P
  • 2. ❏ JDBC is Java application programming interface that allows the Java programmers to access database management system from the java code. ❏ It was developed by JavaSoft, a subsidiary of Sun Microsystems. ❏ It is a java API which enables the java programs to execute SQL statements ❏ JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc. ❏ Generally all Relational Database Management System supports SQL and we all know that Java is platform independent. ❏ So JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems. JDBC?
  • 3. ❏ JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. ❏ It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. JDBC?
  • 4. ODBC (Open Data Base Connectivity) ❏ Open DataBase Connectivity is similar to Java Database Connectivity which is used for accessing and managing database, ❏ but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language
  • 5. The JDBC-ODBC bridge ❏ The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database driver that utilize the ODBC driver to connect the database. ❏ This driver translates JDBC method calls into ODBC function calls. ❏ The Bridge implements Jdbc for any database for which an Odbc driver is available. ❏ The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a native library used to access ODBC.
  • 6. ❏ There are four types of JDBC drivers: ❏ JDBC-ODBC Bridge Driver, ❏ Native Driver, ❏ Network Protocol Driver, and ❏ Thin Driver
  • 7. 1) JDBC-ODBC bridge driver ❏ The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. ❏ This is now discouraged because of thin driver. ❏ Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge. ❏ Advantages: ❏ easy to use. ❏ can be easily connected to any database. ❏ Disadvantages: ❏ Performance degraded because JDBC method call is converted into the ODBC function calls. ❏ The ODBC driver needs to be installed on the client machine.
  • 8. 2) Native-API driver ❏ The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.. Advantages: ❏ performance upgraded than JDBC-ODBC bridge driver. Disadvantages: ❏ The Native driver needs to be installed on the each client machine. ❏ The Vendor client library needs to be installed on client machine.
  • 9. 3) Network Protocol driver ❏ The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. Advantages: #No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc. Disadvantages: #Network support is required on client machine. #Requires database-specific coding to be done in the middle tier. #Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.
  • 10. 4) Thin driver ❏ The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language. Advantages: #Better performance than all other drivers. #No software is required at client side or server side. Disadvantages: #Drivers depend on the Database
  • 11. JDBC ❏ The JDBC API supports both two-tier and three-tier models for database access. ❏ Two-tier model -- a Java applet or application interacts directly with the database. ❏ Three-tier model -- introduces a middle-level server for execution of business logic: ❏ the middle tier to maintain control over data access. ❏ the user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls.
  • 13. JDBC API ❏ The JDBC API provides the facility for accessing the relational database from the Java programming language. ❏ The user not only execute the SQL statements, retrieve results, and update the data but can also access it anywhere within a network because of it's "Write Once, Run Anywhere" (WORA) capabilities. ❏ Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or flat files even in the a heterogeneous environment. ❏ JDBC application programming interface is a part of the Java platform that have included Java SE and Java EE in itself. ❏ The latest version of JDBC 4.0 application programming interface is divided into two packages. i) java.sql. ii) javax.sql. ❏ Java SE and Java EE platforms are included in both the packages.
  • 14. JDBC Driver Manager ❏ The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. ❏ Usually Driver Manager is the backbone of the JDBC architecture. ❏ It's very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application ❏ The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. ❏ The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected.
  • 15. JDBC Driver Manager (contn) ❏ The function of JDBC driver test suite is to make ensure that the JDBC drivers will run user's program or not . ❏ The test suite of JDBC application program interface is very useful for testing a driver based on JDBC technology during testing period. ❏ It ensures the requirement of Java Platform Enterprise Edition (J2EE).
  • 16. Database A Database is a collection of related data organised in a way that data can be easily accessed, managed and updated. Database can be software based or hardware based, with one sole purpose, storing data. DBMS A DBMS is a software that allows creation, definition and manipulation of database, allowing users to store, process and analyse data easily. DBMS provides us with an interface or a tool, to perform various operations like creating database, storing data in it, updating data, creating tables in the database and a lot more. DBMS also provides protection and security to the databases. It also maintains data consistency in case of multiple users. Here are some examples of popular DBMS used these days: - MySql - Oracle - SQL Server - IBM DB2
  • 17. SQL Package ❏ Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language. ❏ This API includes a framework whereby different drivers can be installed dynamically to access different data sources. ❏ Although the JDBCTM API is mainly geared to passing SQL statements to a database, it provides for reading and writing data from any data source with a tabular format. ❏ The reader/writer facility, available through the javax.sql.RowSet group of interfaces, can be customized to use and update data from a spread sheet, or any other tabular data source
  • 18. CONTENTS OF SQL PACKAGE ❏ The java.sql package contains API for the following: 1. Making a connection with a database via the DriverManager facility
  • 19. CONTENTS OF SQL PACKAGE 2. Sending SQL statements to a database 3. Retrieving and updating the results of a query - ResultSet interface Class or Interface
  • 20. CONTENTS OF SQL PACKAGE 4. Standard mappings for SQL types to classes and interfaces in the Java programming language
  • 21. CONTENTS OF SQL PACKAGE 5. Custom mapping an SQL user-defined type (UDT) to a class in the Java 6. Metadata
  • 22. CONTENTS OF SQL PACKAGE 7.Exceptions
  • 24. DriverManager Class Following are the methods of DriverManager class: 1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class. 2. registerDriver(Driver driver) :It registers the driver with the DriverManager class. 3. getConnection(String url) : It tries to establish the connection to a given database URL. 4. getConnection(String url, String user, String password) : It tries to establish the connection to a given database URL. 5. getConnection(String url, Properties info) : It tries to establish the connection to a given database URL. 6. getDriver(String url) : It attempts to locate the driver by the given string. 7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class.
  • 25. SEVEN BASIC STEPS IN ESTABLISHING CONNECTION WITH DATABASE 1. Import package 2. Load and register the driver. 3. Establish the Connection. 4. Create a Statement object. 5. Execute a Query. 6. Process the results. 7. Close the connection.
  • 26. STEP 1-Import package - java.sql: Provides the API for accessing and processing data stored in a data source (usually a relational database) using the JavaTM programming language.This API includes a framework whereby different drivers can be installed dynamically to access different data sources. Although the JDBCTM API is mainly geared to passing SQL statements to a database, it provides for reading and writing data from any data source with a tabular format. - javax.sql: Provides the API for server side data source access and processing from the JavaTM programming language. This package supplements the java.sql package and, as of the version 1.4 release, is included in the Java Platform, Standard Edition (Java SETM). It remains an essential part of the Java Platform, Enterprise Edition (Java EETM).The reader/writer facility, available through the javax.sql.RowSet group of interfaces, can be customized to use and update data from a spread sheet, flat file, or any other tabular data source
  • 27. STEP 2-Load and register the driver A. Load Driver - Which driver loads based on which database we are going to connecting with Eg:- For mysql com.mysql.jdbc.Driver - To load the driver we have to Download it Eg:- For mysql Mysql connector from mysql website A. Register Driver - To register we have to use method forName() Eg:- Syntax of Class.forName() method: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); For mysql class.forName(“com.mysql.jdbc.Driver”);
  • 28. STEP 3-Establish connection - After registering and loading the driver, - we will create a connection using getConnection() method of DriverManager class. - This method has several overloaded methods that can be used based on the requirement. - Basically it require the database name, username and password to establish connection. Syntax getConnection(String url) getConnection(String url, String username, String password) getConnection(String url, Properties info) For Example:- Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:XE","usrnme", "password");
  • 29. STEP 4- Create SQL Statement ❏ You need to create a Statement object to send requests to and retrieve results from a database. ❏ The Connection object provides the createStatement () method to create a Statement object. ❏ It is used to execute the sql queries and defined in Connection class. Syntax of the method is given below. public Statement createStatement() throws SQLException Example to create a SQL statement Statement s=con.createStatement();
  • 30. STEP 5- Execute SQL Statement ❏ After creating statement, now execute using executeQuery() method of Statement interface. ❏ This method is used to execute SQL statements. Syntax of the method is given below. Syntax of the method is given below. public ResultSet executeQuery(String query) throws SQLException Example to create a SQL statement ResultSet rs=s.executeQuery("select * from user");
  • 31. STEP 6- Process the results. ❏ Process the Result In this step we receives the result of execute statement. In this case we will fetch the student records from the recordset object and show on the command prompt. Here is the code: // 1 2 //rollno name Example to create a SQL statement while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); //System.out.println(rs.getInt(“Rollno”)+" "+rs.getString(2)); } Rollno Name Student
  • 32. STEP 7- Closing the connection ❏ This is final step which includes closing all the connection that we opened in our previous steps. ❏ After executing SQL statement you need to close the connection and release the session. ❏ The close() method of Connection interface is used to close the connection. Syntax of the method is given below. public void close() throws SQLException Example to create a SQL statement con.close();
  • 33. Example import java.sql.*; class Test { public static void main(String[] args) { try { //Loading driver Class.forName("oracle.jdbc.driver.OracleDriver"); //creating connection Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "usrname", "pssword"); Statement s = con.createStatement(); //creating statement ResultSet rs = s.executeQuery("select * from Student"); //executing statement while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2)); } con.close(); //closing connection } catch (Exception e) { e.printStacktrace(); } } }
  • 34. ResultSet Interface - The object of ResultSet maintains a cursor pointing to a row of a table. - Initially, cursor points to before the first row. - By default, ResultSet object can be moved forward only and it is not updatable. - But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); Type Description ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set. ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result set is sensitive to changes made by others to the database that occur after the result set was created.
  • 35. ResultSet Interface - Methods Type Description 1) public boolean next(): is used to move the cursor to the one row next from the current position. 2) public boolean previous(): is used to move the cursor to the one row previous from the current position. 3) public boolean first(): is used to move the cursor to the first row in result set object. 4) public boolean last(): is used to move the cursor to the last row in result set object. 5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object. 6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. 7) public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int. 8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int. 9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String. 10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.
  • 36. Example import java.sql.*; class FetchRecord{ public static void main(String args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs=stmt.executeQuery("select * from employee"); //getting the record of 4th row rs.absolute(4); System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); con.close(); }} the simple example of ResultSet interface to retrieve the data of 4th row.
  • 37. SQL Insert ,Create, Update and Delete String str = “INSERT INTO authors (au_id, au_lname) VALUES (‘998’,’ABC’)” ; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); String str = “DELETE FROM authors WHERE lname=‘ABC’ ” ; String str = “CREATE TABLE MyProduct” + “ (p_id INTEGER, ” + ”p_name VARCHAR(25), ” + “rate FLOAT ,” + “unit_msr CHAR (6) )” ;
  • 38. Handling SQL Exceptions ❏ The java.sql package provides the SQLException class , which is derived from the java.lang.Exception class. ❏ The SQLException is thrown by various methods in the JDBC API and enables you to determine the reason of the errors that occur while connecting a Java application to a database. ❏ You can catch the SQLException in a Java application using the try and catch exception handling block. ❏ The methods in the SQLException class are : - int getErrorCode () : Returns the error code associated with the error occurred. - String getSQLState() : X/Open error code. - SQLException getNextException () : Returns the next exceptions in the chain of exceptions.
  • 39. Handling SQL Exceptions -Example try { String str = “DELETE FROM authors WHERE au_id = ‘123’ ” ; Statement stmt = con.createStatement(); int count = stmt.executeUpdate (str) ; } catch (SQLException sqlexception) { System.out.println (“Display Error Code”) ; System.out.println( “SQL Exception” + sqlexception.getErrorCode ()) ; }
  • 40. Example import java.sql.*; public class JDBCStmt { public static void main(String[] args) { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); // Loading driver // Creating connection Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", "root", "admin") Statement stmt = con.createStatement(); // creating Statement boolean flag = stmt.execute("Update Employee set age = 40 where id in (5, 6)"); /** execute method **/ if(flag == false){ System.out.println("Updated rows " + stmt.getUpdateCount() ); } /** executeUpdate method **/ int count = stmt.executeUpdate("Insert into employee(name, age) values('Kim', 23)"); // Insert System.out.println("Rows Inserted " + count); count = stmt.executeUpdate("Update Employee set age = 35 where id = 17"); // update System.out.println("Rows Updated " + count);
  • 41. /** executeQuery method **/ ResultSet rs = stmt.executeQuery("Select * from Employee"); // Executing Query while(rs.next()){ // Processing Resultset System.out.println("id : " + rs.getInt("id") + " Name : " + rs.getString("name") + " Age : " + rs.getInt("age")); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(connection != null){ //closing connection try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // if condition } // finally } } Example
  • 42. Statement interface ❏ Statement interface resides in java.sql package and it is used to execute a static SQL statement and returning the result of the executed query. ❏ Statement interface has two sub-interfaces CallableStatement and PreparedStatement. ❏ get a Statement object by calling the Connection.createStatement() method on the Connection object.
  • 43. Statement interface Methods The Statement interface provides various methods 1. boolean execute(String sql) : Executes the given SQL statement (it can be any kind of SQL query), which may return multiple results. Returns a boolean which is true if the first result is a ResultSet object; false if it is an update count or there are no results. 2. ResultSet executeQuery(String sql): Executes the given SQL statement, which returns a single ResultSet object. If you want to execute a Select SQL query which returns results you should use this method. 3. int executeUpdate(String sql): Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.Returns an int denoting either the row count for the rows that are inserted, deleted, updated or returns 0 if nothing is returned. Note:This method cannot be called on a PreparedStatement or CallableStatement. 4. int[] executeBatch(): Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.
  • 44. PreparedStatement interface ❏ The PreparedStatement objects accepts the runtime parameters. ❏ The PreparedStatement interface is derived from the Statement interface and is available in the java.sql package. ❏ The PreparedStatement objects are compiled and prepared only once by JDBC. The future invocation of the PreparedStatement object does not recompile the SQL statements. ❏ This helps in reducing the load on the database server and thus improving the performance of the application .
  • 45. PreparedStatement interface ❏ The PreparedStatement interface inherits the following methods to execute SQL statement s 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.
  • 46. PreparedStatement interface stat = con.prepareStatement(“SELECT * FROM authors WHERE au_id = ? ”) ; The SQL statement can contain ‘ ? ‘ symbol as placeholder that can be replaced by input parameters at runtime. Before executing the SQL statements specified in the PreparedStatement object , you must set the value of each ‘ ? ‘ parameter. This is done by calling an appropriate setXXX () method , where XXX is the data type of the parameter. stat.setString (1, “123”); ResultSet rs = stat.executeQuery ();
  • 47. PreparedStatement interface Methods The PreparedStatement interface provides various methods to set the value of the placeholders for the specific data types. 1. void setByte (int index , byte val) : Sets the java byte type value for the parameter corresponding to index passed as a parameter. 2. void setBytes (int index , byte[] val) : Sets the Java byte type array for the parameter corresponding to index passed as a parameter. 3. void setBoolean (int index , boolean val) : Sets the Java boolean type value for the parameter corresponding to index passed as a parameter. 4. void setDouble (int index, double val) : Sets the Java double type value value for the parameter corresponding to the index passed as a parameter.
  • 48. PreparedStatement interface Methods 5. void setInt (int index , int val) : Sets the Java int type value for the parameter corresponding to index passed as a parameter. 6. void setLong(int index , long val) : Sets the Java long type value for the parameter corresponding to index passed as a parameter. 7. void setFloat (int index , float val) : Sets the Java float type value for the parameter corresponding to index passed as a parameter. 8. void setShort (int index , short val) : Sets the Java short type value for the parameter corresponding to index passed as a parameter. 9. void setString(int index , String val) : Sets the Java String type value for the parameter corresponding to index passed as a parameter.
  • 49. Retrieving Rows String str = “SELECT * FROM titles WHERE au_id = ? ” ; PreparedStatement ps = con.prepareStatement(str) ; ps.setString(1 , “101”); ResultSet rs = ps.executeQuery ();
  • 50. Inserting Rows String str = “ INSERT INTO authors (au_id , au_fname , au_lname) VALUES (? , ? , ? ) ” ; ps = con.prepareStatement(str); ps.setString (1, “101”); ps.setString (2, “ABC”); ps.setString (3 , “XYZ”); int rt = ps.executeUpdate() ;
  • 51. Updating & Deleting Row String str = “ UPDATE authors SET state = ? WHERE city = ? “ ; PreparedStatement ps = con.prepareStatement(str); ps.setString (1, “MH”); ps.setString (2, “Pune”); int rt = ps.executeUpdate() ; String str = “ DELETE FROM authors WHERE au_fname = ? “ ; PreparedStatement ps = con.prepareStatement(str); ps.setString (1, “PPPP”); int rt = ps.executeUpdate() ;
  • 52. Creating Stored Procedures ❏ You can use the executeUpdate () to execute the CREATE PROCEDURE SQL statement. ❏ Stored procedures can be of two types , parameterized and non- parameterized. Non – parameterized stored procedure in a JDBC application: ❏ When you use the stored procedures to perform database operations, it reduces network traffic because instead of sending multiple SQL statements to a database , a single stored procedure is executed. String str = “ CREATE PROCEDURE authors_info” + “AS” + “SELECT au_id , au_lname , au_fname” + ”FROM authors” + “WHERE city = ‘Pune’ ” + ”ORDER BY au_fname” ; Statement stmt = con.createStatement () ; int rt = stmt.executeUpdate (str); The Connection object con is used to send the CREATE PROCEDURE SQL statement to a database. When you execute the code , the authors_info stored procedure is created and stored in the database.
  • 53. Creating Stored Procedures You can use the following code snippet to create a parameterized stored procedure. String str = “ CREATE PROCEDURE authors_info_prmtz @auth_id varchar(15) , @auth_fname varchar(20) output , @auth_lname varchar(20) output , @auth_city varchar(20) output , @auth_state varchar(20) output ” + “AS” + “SELECT @auth_fname = au_fname , @auth_lname = au_lname , @auth_city = city , @auth_state = state ” + “ FROM authors ” + “ WHERE au_id = @auth_id ” ; Statement stmt = con.createStatement () ; int rt = stmt.executeUpdate (str);
  • 54. Creating Stored Procedures - In the preceding code snippet , the authors_info_prmtz stored procedure is created that accepts author id as parameter and retrieve the corresponding author information form the database. - The retrieved information is stored in the OUT parameter. The SQL Server 2000 uses output keyword to represent OUT parameters. - A stored procedure can accepts one or multiple parameters. - A parameter of a stored procedure can take any of these forms : 1. IN : Refers to the argument that you pass to a stored procedure. 2. OUT : Refers to the return value of a stored procedure. 3. 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
  • 55. Calling a Stored Procedure without Parameters - The Connection interface provides the prepareCall() method that is used to create the CallableStatement object . - This object is used to a call a stored procedure of a database . - The prepareCall () is an overloaded method that has the following 3 forms: 1. CallableStatement prepareCall (String str) : Creates a CallableStatement object to call a stored procedure. The prepareCall () accepts a string as a parameter that contains an SQL statement to call a stored procedure. You can also specify the placeholders to accept parameters in the SQL statement. 2. CallableStatement prepareCall(String str , int resSetType , int resSetConc): Creates a CallableStatement object that returns ResultSet object that has the specified result set type and concurrency mode. The method accepts following 3 parameter : String object :Contains the SQL statement to call a stored procedure. The SQL statement can contains one or more parameters. ResultSet types : Specifies any of the 3 result set types , TYPE_FORWARD_ONLY , TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE. ResultSet concurrency modes :Specifies either of these concurrency modes , CONCUR_READ_ONLY or CONCUR_UPDATABLE , for a result set
  • 56. Calling a Stored Procedure without Parameters 3. CallableStatement prepareCall (String str , int resSetType , int resSetConcur , int resSetHoldability) : Creates a CallableStatement object that returns a ResultSet object . This ResultSet object has the specified result type, concurrency mode, and constant to set the result set state. The syntax to call a stored procedure without parameter is : { call <procedure_name> } ; Eg: String str = “ {call authors_info}” ; CallableStatement cs = con.prepareCall (str) ; ResultSet rs = cs.executeQuery() ; while(rs.next()) { System.out.println(“Author ID :” + rs.getString(1) + “t”); System.out.println(“Author First Name :” + rs.getString(2) + “t”); System.out.println(“Author Last Name :” + rs.getString(3) + “t”); }
  • 57. Calling a Stored Procedure with Parameters - The SQL escape syntax is used to call a stored procedure with parameters. - There are two forms of the SQL escape syntax, one that contains result parameter and one that does not. - If the SQL escape syntax contains a result parameter, the result parameter is used to return a value from a stored procedure. - The result parameter is an OUT parameter. Other parameters of the SQL escape syntax can contain IN , OUT , or INOUT parameters. - The syntax to call a stored procedure with parameter is : { call <procedure_name> (?)} ; - You need to set the value of the IN parameters before the CallableStatement object executed , otherwise the SQLException is thrown while processing the stored procedure. <CallableStatement_object>.setInt(<value>)
  • 58. Calling a Stored Procedure with Parameters - If the stored procedure contains OUT and INOUT parameters, these parameters should be registered with corresponding JDBC types before a call to a stored procedures is processed. - The JDBC types determine the Java data types that are used in the get methods while retrieving the values of the OUT and INOUT parameters. cs.registerOutParameter (1 . Java.sql.Types.STRING) ; Accepts the position of the placeholder and a constant in the java.sql.Types class as parameters. cs.registerOutParameter (1, java.sql.Types.DECIMAL , 3) ; What for 3rd Parameter used for ?
  • 59. Calling a Stored Procedure with Parameters import java.sql.*; public class CallProc { public static void main(String arg []) { String id , fname , lname , address , city ; try { String str = “ { call authors_info ( ? , ? , ? , ? , ? ) } ” ; Class.forname (“sun.jdbc.odbc.JdbcOdbcDriver”); Connection con = DriverManager.getConnection(“jdbc:odbc:DSN”) ; CallableStatement cs = con.prepareCall (str) ; cs.setString (1 , “123-456” ) ; // pass IN parameter //Register OUT paramter cs.registerOutParameter(2 , Types.VARCHAR); cs.registerOutParameter(3 , Types.VARCHAR); cs.registerOutParameter(4 , Types.VARCHAR); cs.registerOutParameter(5 , Types.VARCHAR); // process the Stored procedure cs.execute () ; fname = cs.getString(2) ; lname = cs.getString(3) ; address = cs.getString(4) ; city = cs.getString(5) ; ----- ---- }}
  • 60. ResultSetMetaData - The ResultSetMetaData interface contains various methods that enable you to retrieve information about the data in a result set , such as number of columns , names of columns and data types of the columns. - The ResultSet interface provides the getMetaData () method to create an object of the ResultSetMetaData interface . ResultSetMetaData rm = rs.getMetaData() ; The following lists the commonly used methods of the ResultSetMetaData interface : - int getColumnCount () : Returns an integer indicating the total number of columns in a ResultSet object . - String getColumnLabel (int col_index) : Retrieves the title of the table column corresponding to the index passed as a parameter to this method. - String getColumnName (int col_index) : Retrieves the name of the table column corresponding to the index passed as a parameter to this method. - int getColumnType (int col_index) : Retrieves the SQL data type of the table column corresponding to the index passed as a parameter.
  • 61. ResultMetaData - String getTableName(int col_index) : Retrieves the name of the database table that contains the column corresponding to the index passed as a parameter. - boolean isAutoIncrement (int col_index) : Returns a boolean value that indicates whether the table column corresponding to the index passed as a parameter increments automatically. - boolean isCaseSensitive (int col_index) : Returns a boolean value that indicates whether the table column corresponding to the index passed as a parameter is case sensitive. - boolean isReadOnly (int col_index) : Returns a boolean value that indicates whether the column in a ResultSet corresponding to the index passed as a parameter is read only. - boolean isWritable (int col_index) : Returns a boolean value that indicates whether ResultSet column corresponding to the index passed as a parameter is updatable.
  • 62. END