0% found this document useful (0 votes)
5 views

java_unit3

Uploaded by

XeroX PlayzYT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

java_unit3

Uploaded by

XeroX PlayzYT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Java JDBC Tutorial

Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.

Why use JDBC


Before JDBC, ODBC API was the database API to connect and execute query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API can be created for
applications, libraries, operating systems, etc

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver

2. Native-API driver (partially java driver)

3. Network Protocol driver (fully java driver)


4. Thin driver (fully java 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.

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.

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.
Advan
tage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.

o 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.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.

o Requires database-specific coding to be done in the middle tier.

o 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.
Advantage:
o Better performance than all other drivers.

o No software is required at client side or server side.

Disadvantage:
o Drivers depends on the Database.

5 Steps to connect to the database


There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
o Register the driver class

o Creating connection

o Creating statement

o Executing queries

o Closing connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with
the database.

Syntax of getConnection() method


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException

Example to establish connection with the Oracle


database
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","syst
em","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException

Example to create the statement object


1. Statement stmt=con.createStatement();

4) Execute the query


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.

Syntax of executeQuery() method


1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)); }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException

Example to close connection


1. con.close();

Example to connect to the Oracle database


For connecting java application with the oracle database, you need to follow 5 steps to
perform database connectivity. In this example we are using Oracle10g as the database.
So we need to know following informations for the oracle database:

1. Driver class: The driver class for the oracle database


is oracle.jdbc.driver.OracleDriver.

2. Connection URL: The connection URL for the oracle10G database


is jdbc:oracle:thin:@localhost:1521:xewhere jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the Oracle
service name. You may get all these informations from the tnsnames.ora file.

3. Username: The default username for the oracle database is system.

4. Password: Password is given by the user at the time of installing the oracle
database.
Let's first create a table in oracle database.
1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle


database
In this example, system is the username and oracle is the password of the Oracle database.

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);}

}
}
To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.

DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and
the appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().

Commonly used methods of DriverManager class:


1) public static void registerDriver(Driver is used to register the given driver with
driver): DriverManager.

is used to deregister the given driver


2) public static void deregisterDriver(Driver
(drop the driver from the list) with
driver):
DriverManager.

3) public static Connection is used to establish the connection with


getConnection(String url): the specified url.

4) public static Connection is used to establish the connection with


getConnection(String url,String the specified url, username and
userName,String password): password.

Connection interface
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. 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() etc.

By default, connection commits the changes after executing queries.

Commonly used methods of Connection interface:


1) public Statement createStatement(): creates a statement object that can be used
to execute SQL queries.

2) public Statement createStatement(int resultSetType,int


resultSetConcurrency): Creates a Statement object that will generate ResultSet objects
with the given type and concurrency.

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

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:

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.

Example of Statement interface


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","syste
m","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. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface


1) public boolean next(): is used to move the cursor to the one row next from the current positi

2) public boolean previous(): is used to move the cursor to the one row previous from the current p

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 is used to move the cursor to the specified row number in the ResultS
absolute(int row):

6) public boolean relative(int is used to move the cursor to the relative row number in the Result
row): may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of the current row
columnIndex):

8) public int getInt(String is used to return the data of specified column name of the current row
columnName):

9) public String getString(int is used to return the data of specified column index of the current row
columnIndex):

10) public String is used to return the data of specified column name of the current row
getString(String
columnName):

PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.

Why use PreparedStatement?


Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:

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, float sets the float value to the given parameter index.
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.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.

Example of PreparedStatement interface that inserts the record


First of all create table as given below:

create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:

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","syste
m","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);}

}
}

Example of PreparedStatement interface that updates the record


PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);

int i=stmt.executeUpdate();
System.out.println(i+" records updated");

Example of PreparedStatement interface that deletes the record


PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
stmt.setInt(1,101);

int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records
of a table
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

Java Networking
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.

Advantage of Java Networking


1. sharing resources

2. centralize software management

Java Networking Terminology


The widely used java networking terminologies are given below:

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.

It is a logical address that can be changed.


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.

5) Connection-oriented and connection-less protocol


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
A socket is an endpoint between two way communication.

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.

Java Socket programming can be connection-oriented or connection-less.


Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

The client in socket programming must know two information:

1. IP Address of Server, and

2. Port number.

Example of Java Socket Programming


Let's see a simple of java socket programming in which client sends a text and server
receives 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);}
}
}

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);}
}
}

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. http://www.javatpoint.com/java-tutorial

A URL contains many information:

1. Protocol: In this case, http is the protocol.

2. Server name or IP Address: In this case, www.javatpoint.com is the server name.

3. Port Number: It is an optional attribute. If we write


http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is
not mentioned in the URL, it returns -1.

4. File Name or directory name: In this case, index.jsp is the file name.

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 String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.


public URLConnection openConnection() it returns the instance of URLConnection i.e.

associated with this URL.

Example of Java URL class


//URLDemo.java
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

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);}
}
}

Java DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming .

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.

A datagram is basically an information but there is no guarantee of its content, arrival or


arrival time.

Commonly used Constructors of DatagramSocket class


o DatagramSocket() throws SocketEeption: it creates a datagram socket and
binds it with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket
and binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it
creates a datagram socket and binds it with the specified port number and host
address.

Java DatagramPacket class


Java DatagramPacket is a message that can be sent or received. If you send multiple
packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class


o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by


DatagramSocket
//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");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}
Example of Receiving DatagramPacket by
DatagramSocket
//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();
}
}

You might also like