Unit-2 Networking & JDBC
Unit-2 Networking & JDBC
Java Networking is a concept of connecting two or more computing devices together so that we can share resources.
Java socket programming provides facility to share data between different computing devices.
1. Sharing resources
2. Centralize software management
1. TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP
is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to be
transferred along two or more nodes
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range
from 0 to 255.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication endpoint between
applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A network node can
have multiple NIC but each with unique MAC address.
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of
connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.
6) Socket
The java.net package provides many classes to deal with networking applications in Java. A list of these classes is
given below:
o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
o URI
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler
o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily
Java Socket Programming
Java Socket programming is used for communication between the applications running on different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.
Here, we are going to make one-way client and server communication. In this application, client sends a message to
the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The
Socket class is used to communicate client and server. Through this class, we can read and write message. The
ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client
is connected. After the successful connection of client, it returns the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a
socket.
Important methods
Method Description
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication with the
clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection between server
and client.
To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port
number for the communication between the client and server. You may also choose any other port number. The
accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket.
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address
or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same
system.
Let's see a simple of Java socket programming where client sends a text and server receives and prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute each program at each command prompt as
displayed in the below figure.
After running the client application, a message will be displayed on the server console.
ADVERTISEMENT BY ADRECOVER
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the
World Wide Web. For example:
1. https://www.javatpoint.com/java-tutorial
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
Creates an instance of a URL from the given protocol name, host name, and file name.
Creates an instance of a URL by parsing the given spec within a specified context.
Creates an instance of a URL by parsing the given spec with the specified handler within a given context.
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of URL class are given below.
Method Description
public boolean equals(Object obj) it compares the URL with the given object.
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
URLConnection Class
The Java URLConnection class represents a communication link between the URL and
the application. It can be used to read and write data to the specified resource referred
by the URL.
o URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that
helps to find a resource on the World Wide Web (WWW).
o URL has two components:
Constructors
Constructor Description
Method Description
void addRequestProperty(String key, String value) It adds a general request property specified
by a key-value pair
static FileNameMap getFilenameMap() It loads the filename map from a data file.
String getHeaderField(int n) It returns the value of nth header field
long getHeaderFieldDate(String name, long Default) It returns the value of the named field
parsed as a number.
int getHeaderFieldInt(String name, int Default) It returns the value of the named field
parsed as a number.
String getHeaderFieldKey(int n) It returns the key for the nth header field.
long getHeaderFieldLong(String name, long Default) It returns the value of the named field
parsed as a number.
void setDoInput(boolean doinput) It sets the value of the doInput field for this
URLConnection to the specified value.
void setDoOutput(boolean dooutput) It sets the value of the doOutput field for
the URLConnection to the specified value.
Syntax:
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.vvitguntur.com/");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
InetAddress class
InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host
name for example www.javatpoint.com, www.google.com, www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP
address with its corresponding host name. There are two types of addresses: Unicast and Multicast. The Unicast is an
identifier for a single interface whereas Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions.
IP Address
o An IP address helps to identify a specific resource on the network using a numerical representation.
o Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge among the
destination and the source.
1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARAPNET in 1983. It is a
widely used IP version to differentiate devices on network using an addressing scheme. A 32-bit addressing scheme is
used to store 232 addresses that is more than 4 million addresses.
Features of IPv4:
o It is a connectionless protocol.
o It utilizes less memory and the addresses can be remembered easily with the class based addressing scheme.
o It also offers video conferencing and libraries.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It provides
solutions for the problems present in IPv4. It provides 128-bit address space that can be used to form a network of
340 undecillion unique IP addresses. IPv6 is also identified with a name IPng (Internet Protocol next generation).
Features of IPv6:
o It has a stateful and stateless both configurations.
o It provides support for quality of service (QoS).
o It has a hierarchical addressing and routing infrastructure.
Example
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");
Datagram
Datagrams are collection of information sent from one device to another device via the established network. When
the datagram is sent to the targeted device, there is no assurance that it will reach to the target device safely and
completely. It may get damaged or lost in between. Likewise, the receiving device also never know if the datagram
received is damaged or not. The UDP protocol is used to implement the datagrams in Java.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.
void connect(InetAddress It connects the socket to a remote address for the socket.
address, int port)
InetAddress getLocalAddress() It gets the local address to which the socket is connected.
int getLocalPort() It returns the port number on the local host to which the
socket is bound.
int getPort() It returns the port number to which the socket is connected.
int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this
DatagramSocket that is the buffer size used by the platform
for input on the DatagramSocket.
4) int getOffset() It returns the offset of the data to be sent or the offset
of the data received.
7) void setAddress(InetAddress iaddr) It sets the IP address of the machine to which the
datagram is being sent.
8) void setData(byte[] buff) It sets the data buffer for the packet.
10) void setPort(int iport) It sets the port number on the remote host to which
the datagram is being sent.
//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
Output:
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
Output:
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. There are four
types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save,
update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL
Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of
JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
o DriverManager class
o Blob class
o Clob class
o Types class
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
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:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.
ADVERTISEMENT BY ADRECOVER
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.
Advantage:
Disadvantage:
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
Advantage:
Disadvantage:
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the classpath, and t hen
JDBC driver manager can detect and load the driver automatically.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the
database.
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
1. Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close resources of type
Connection, ResultSet, and Statement.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
DriverManager class
The DriverManager class is the component of JDBC API and also a member of the java.sql package. The
DriverManager class acts as an interface between users and drivers. It keeps track of the drivers that are available and
handles establishing a connection between a database and the appropriate driver. It contains all the appropriate
methods to register and deregister the database driver class and to create a connection between a Java application
and the database. The DriverManager class maintains a list of Driver classes that have registered themselves by calling
the method DriverManager.registerDriver(). Note that before interacting with a Database, it is a mandatory process to
register the driver; otherwise, an exception is thrown.
Methods of the DriverManager Class
Method Description
1)public static synchronized is used to register the given driver with DriverManager.
void registerDriver(Driver No action is performed by the method when the given
driver) driver is already registered.
2)public static synchronized is used to deregister the given driver (drop the driver
void deregisterDriver(Driver from the list) with DriverManager. If the given driver has
driver) been removed from the list, then no action is performed
by the method.
3) public static Connection is used to establish the connection with the specified url.
getConnection(String url) The SQLException is thrown when the corresponding
throws SQLException Driver class of the given database is not registered with
the DriverManager.
4) public static Connection is used to establish the connection with the specified url,
getConnection(String url,String username, and password. The SQLException is thrown
userName,String password) when the corresponding Driver class of the given
throws SQLException database is not registered with the DriverManager.
5) public static Driver Those drivers that understand the mentioned URL
getDriver(String url) (present in the parameter of the method) are returned by
this method provided those drivers are mentioned in the
list of registered drivers.
6) pubic static int The duration of time a driver is allowed to wait in order to
getLoginTimeout() establish a connection with the database is returned by
this method.
7) pubic static void The method provides the time in seconds. sec mentioned
setLoginTimeout(int sec) in the parameter is the maximum time that a driver is
allowed to wait in order to establish a connection with the
database. If 0 is passed in the parameter of this method,
the driver will have to wait infinitely while trying to
establish the connection with the database.
Connection interface
A Connection is a session between a Java application and a database. It helps to establish a connection with the
database.
The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData, i.e., an object of
Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide
many methods for transaction management like commit(), rollback(), setAutoCommit(), setTransactionIsolation(), etc.
1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.
3) public void setAutoCommit(boolean status): is used to set the commit status. By default, it is true.
4) public void commit(): saves the changes made since the previous commit/rollback is permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement interface is a factory
of ResultSet i.e. it provides factory method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.
Let’s see the simple example of Statement interface to insert, update and delete the record.
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();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}
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:
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 is used to move the cursor to the specified row number in
row): the ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row number in
row): the ResultSet object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the
columnIndex): current row as int.
8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
10) public String is used to return the data of specified column name of the
getString(String columnName): current row as String.
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of
PreparedStatement.
Improves performance: The performance of the application will be faster if you use PreparedStatement interface
because query is compiled only once.
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)
public void setString(int paramIndex, sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, sets the float value to the given parameter index.
float value)
public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
ResultSetMetaData Interface
metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.
public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as database product name,
database product version, driver name, name of total number of tables, name of total number of views etc.
The getMetaData() method of Connection interface returns the object of DatabaseMetaData. Syntax:
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
CallableStatement Interface
CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and functions that will make the
performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a function that
receives date as the input and returns age of the employee as the output.
The differences between stored procedures and functions are given below:
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output Function supports only input parameter.
parameters.
Exception handling using try/catch block can Exception handling using try/catch can't be
be used in stored procedures. used in user defined functions.
The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below:
BEGIN
END
Program
Import java.sql.*;
class JdbcCallableTest
try{
class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”manager”);
boolean b=csmt.execute();
con.close();
}catch(Exception e)
System.out.println(e);