UNIT 3
UNIT 3
3.1 JDBC
3.1.1 INTRODUCTION
JDBC stands for Java Database Connectivity, which is a standard Java
API for database-independent connectivity between the Java programming
language and a wide range of databases.The JDBC library includes APIs for
each of the tasks mentioned below that are commonly associated with
database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database. Java
can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to
access a database, and take advantage of the stored data.JDBC provides the
same capabilities as ODBC, allowing Java programs to contain database-
independent code.
Driver :This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.
Connection:This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
Statement :You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
The java.sql and javax.sql are the primary packages for JDBC 4.0. This
is the latest JDBC version at the time of writing this tutorial. It offers the main
classes for interacting with your data sources. The new features in these
packages include changes in the following areas :
Password: It is the password given by the user at the time of installing the
mysql database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating
table, we need to create database first.
use sonoo;
In this example, sonoo is the database name, root is the username and
password both.
import java.sql.*;
class MysqlCon{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
Statement stmt=con.createStatement();
while(rs.next())
con.close();
The above example will fetch all the records of emp table.
temporary
permanent
How to set the temporary classpath
C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Statement stmt=con.createStatement();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
CREATE DATABASE – create the database. To use this statement, you need
the CREATE privilege for the database.
CREATE TABLE :create the table. You must have the CREATE privilege for
the table.
INSERT –:To add/insert data to table i.e. inserts new rows into an existing
table.
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages containing
the JDBC classes needed for database programming. Most often, using
import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection()
method to create a Connection object, which represents a physical
connection with the database server.
To create a new database, you need not give any database name while
preparing database URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for building
and submitting an SQL statement to the database.
Sample Code
Copy and paste the following example in JDBCExample.java, compile and run
as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
Method Description
Example
root@localhost
jdbc:mysql://localhost/sampleDB
Numeric functions:
ABS,ACOS,ASIN,ATAN,ATAN2,BIT_COUNT,CEILING,COS,COT,DEGREES,EXP,FL
OOR,LOG,LOG10,MAX
,MIN,MOD,PI,POW,POWER,RADIANS,RAND,ROUND,SIN,SQRT,TAN,TRUNCATE
String functions:
ASCII,BIN,BIT_LENGTH,CHAR,CHARACTER_LENGTH,CHAR_LENGTH,CONCAT,C
ONCAT_WS,CONV,ELT,E
XPORT_SET,FIELD,FIND_IN_SET,HEX,INSERT,INSTR,LCASE,LEFT,LENGTH,LOAD
_FILE,LOCATE,LO
CATE,LOWER,LPAD,LTRIM,MAKE_SET,MATCH,MID,OCT,OCTET_LENGTH,ORD,P
OSITION,QUOTE,REPEA
T,REPLACE,REVERSE,RIGHT,RPAD,RTRIM,SOUNDEX,SPACE,STRCMP,SUBSTRIN
G,SUBSTRING,SUBSTR
ING,SUBSTRING,SUBSTRING_INDEX,TRIM,UCASE,UPPER
System functions:
DATABASE,USER,SYSTEM_USER,SESSION_USER,PASSWORD,ENCRYPT,LAST_I
NSERT_ID,VERSION
DAYOFWEEK,WEEKDAY,DAYOFMONTH,DAYOFYEAR,MONTH,DAYNAME,MONTH
NAME,QUARTER,WEEK,YEAR,H
OUR,MINUTE,SECOND,PERIOD_ADD,PERIOD_DIFF,TO_DAYS,FROM_DAYS,DAT
E_FORMAT,TIME_FORMAT
,CURDATE,CURRENT_DATE,CURTIME,CURRENT_TIME,NOW,SYSDATE,CURREN
T_TIMESTAMP,UNIX_TIME
STAMP,FROM_UNIXTIME,SEC_TO_TIME,TIME_TO_SEC3.9 INTRODUCTION TO
The java.net package provides support for two protocols. They are as
follows:
IP Address
Protocol
Port Number
MAC Address
Connection-oriented and connection-less protocol
Socket
Now let’s get into the details of each of these methods.
IP Address
Protocol
Port Number
MAC Address
An attempt is made, for connecting the client to the server using the
specified IP address and port number. If attempt is successful, client is
provided with a Socket that is capable of communicating to the respective
server, with write and read methods. If unsuccessful, desired exception is
raised.
Once the communication is completed, terminate the sockets on both, the
server and the client side.
Connection:
Communication
The communication is held using the output and input streams. These
streams are responsible for transmitting the information in the form of byte
array. An object can also be transmitted through these streams, but it needs
to be serialized before transmitting and deserialized after it has been
received. Input and output streams are made available through socket
instances.
Terminating Connection:
Implementation:
import java.io.*;
import java.net.*;
class Client
{
public static void main(String data[])
{
//data is taken as command line argument
String ipAddress=data[0];
int portNumber=Integer.parseInt(data[1]);
int rollNumber=Integer.parseInt(data[2]);
String name=data[3];
String gender=data[4];
String request=rollNumber+”,”+name+”,”+gender+”#”;
//”#” acts as a terminator
try
{
Socket socket=new Socket(ipAddress , portNumber);
// Socket is initialized and attempt is made for connecting to the server
// Declaring other properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
int x;
// retrieving output Stream and its writer, for sending request or
acknowledgement
outputStream=socket.getOutputStream();
outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(request);
outputStreamWriter.flush(); // request is sent
// retrieving input stream and its reader, for receiving acknowledgement or
response
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x==’#’ || x==-1) break; // reads till the terminator
stringBuffer.append((char)x);
}
response=stringBuffer.toString();
System.out.println(response);
socket.close(); //closing the connection
}catch(Exception exception)
{
// Raised in case, connection is refused or some other technical issue
System.out.println(exception);
}}
}
Server Side Programming
For the server side programming, a ServerSocket is required, that will
wait for the client in the listening mode, on a particular TCP port. This
ServerSocket holds until a Client Socket is connected successfully. As soon
as the client is connected, another Socket comes to the existence that will
enable data sharing between the respective client and server.
Creating ServerSocket:
Communication:
Terminating Connection:
Once the response is sent, the socket, along with the input and output
streams needs to be closed explicitly.
Implementation:
import java.io.*;
import java.net.*;
class RequestProcessor extends Thread //for multi-threaded server
{
private Socket socket;
RequestProcessor(Socket socket)
{
this.socket=socket;
start(); // will load the run method
}
public void run()
{
try
{
//Declaring properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
String request;
int x;
int temp1,temp2;
String part1,part2,part3;
int rollNumber;
String name;
String gender;
//getting input stream and its reader, for reading request or
acknowledgement
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x=='#' || x==-1) break; //reads until terminator
stringBuffer.append((char)x);
}
request=stringBuffer.toString();
System.out.println("Request : "+request);
//parsing and extracting Request data
temp1=request.indexOf(",");
temp2=request.indexOf(",",temp1+1);
part1=request.substring(0,temp1);
part2=request.substring(temp1+1,temp2);
part3=request.substring(temp2+1);
rollNumber=Integer.parseInt(part1);
name=part2;
gender=part3;
System.out.println("Roll number : "+rollNumber);
System.out.println("Name : "+name);
System.out.println("Gender : "+gender);
// handle data
//sending response
response="Data saved#";
//get output stream and its writer, for sending response or acknowledgement
outputStream=socket.getOutputStream();
outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(response);
outputStreamWriter.flush(); // response sent
System.out.println("Response sent");
socket.close(); //terminating connection
}catch(Exception exception)
{
System.out.println(exception);
}
}}
class Server
{
private ServerSocket serverSocket;
private int portNumber;
Server(int portNumber)
{
this.portNumber=portNumber;
try
{
//Initiating ServerSocket with TCP port
serverSocket=new ServerSocket(this.portNumber);
startListening();
}catch(Exception e)
{
System.out.println(e);
System.exit(0);
}}
private void startListening()
{
try
{
Socket socket;
while(true)
{
System.out.println("Server is listening on port : "+this.portNumber);
socket=serverSocket.accept(); // server is in listening mode
System.out.println("Request arrived..");
// diverting the request to processor with the socket reference
new RequestProcessor(socket);
}
}catch(Exception e)
{
System.out.println(e);
}
} public static void main(String data[])
{
int portNumber=Integer.parseInt(data[0]);
Server server=new Server(portNumber);
}}
Execution:
To run, compile the server and client code. First, start server in prompt like
this:
After the data is sent from client, server prompt will look like this:
UDP Sockets
socket() - Firstly a socket is defined in both server and client. This need not
happen at the same time. For the explanation to be comprehensive, I will be
discussing the actions of both server and client in each stage.
recvfrom() -After binding to a port in the machine, the server socket waits
for a connection from a client socket. In the meantime, further execution of
the current thread is halt (blocked) until the server socket receives a
connection. This is the same for the client socket when waiting for a server
response.
sendto() - After connecting with a client, the server socket sends data to
the client. This same method is used by the client socket to make a
connection request to the server.
close() - After successful data exchange, both sockets are closed i.e. system
resources allocated for the sockets are released.
In this example, the socket server receives data of type String from the client
and sends the capitalized string back to the client.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPServer{
public final static int SERVICE_PORT=50001;
public static void main(String[] args) throws IOException{
try{
DatagramSocket serverSocket = new DatagramSocket(SERVICE_PORT);
byte[] receivingDataBuffer = new byte[1024];
byte[] sendingDataBuffer = new byte[1024];
DatagramPacket inputPacket = new DatagramPacket(receivingDataBuffer,
receivingDataBuffer.length);
System.out.println("Waiting for a client to connect...");
serverSocket.receive(inputPacket);
String receivedData = new String(inputPacket.getData());
System.out.println("Sent from the client: "+receivedData);
sendingDataBuffer = receivedData.toUpperCase().getBytes();
InetAddress senderAddress = inputPacket.getAddress();
int senderPort = inputPacket.getPort();
DatagramPacket outputPacket = new DatagramPacket(sendingDataBuffer,
sendingDataBuffer.length,senderAddress,senderPort);
serverSocket.send(outputPacket);
serverSocket.close();
}
catch (SocketException e){
e.printStackTrace();
}}
}
Creating the UDP socket client:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient{
public final static int SERVICE_PORT = 50001;
public static void main(String[] args) throws IOException{
try{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendingDataBuffer = new byte[1024];
byte[] receivingDataBuffer = new byte[1024];
String sentence = "Hello from UDP client";
sendingDataBuffer = sentence.getBytes();
DatagramPacket sendingPacket = new
DatagramPacket(sendingDataBuffer,sendingDataBuffer.length,IPAddress,
SERVICE_PORT);
clientSocket.send(sendingPacket);
DatagramPacket receivingPacket = new
DatagramPacket(receivingDataBuffer,receivingDataBuffer.length);
clientSocket.receive(receivingPacket);
String receivedData = new String(receivingPacket.getData());
System.out.println("Sent from the server: "+receivedData);
clientSocket.close();
}
catch(SocketException e) {
e.printStackTrace();
}
}}
UDPServer.java
UDPClient.java
A URL can have many forms. The most general however follows three-
components system-
Protocol: HTTP is the protocol here
Creates a URL by parsing the given spec with the specified handler within a
specified context.
Program:
import java.net.MalformedURLException;
import java.net.URL;
public class URLclass1
{
public static void main(String[] args)
throws MalformedURLException
{
URL url1 = new URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYq" +
"WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
URL url2 = new URL("http", "www.geeksforgeeks.org", kjsxdfef "/jvm-works-
jvm-architecture/");
URL url3 = new URL("https://www.google.co.in/search?"+
"q=gnu&rlz=1C1CHZL_enIN71" +"4IN715&oq=gnu&aqs=chrome..69i57j6" +
"9i60l5.653j0j7&sourceid=chrome&ie=UTF" +"-
8#q=geeks+for+geeks+java");
System.out.println(url1.toString());
System.out.println(url2.toString());
System.out.println();
System.out.println("Different components of the URL3-");
System.out.println("Protocol:- " + url3.getProtocol());
System.out.println("Hostname:- " + url3.getHost());
System.out.println("Default port:- " +url3.getDefaultPort());
System.out.println("Query:- " + url3.getQuery());
System.out.println("Path:- " + url3.getPath());
System.out.println("File:- " + url3.getFile());
System.out.println("Reference:- " + url3.getRef());
}
}
Output:
https://www.google.co.in/?
gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java
https://www.geeksforgeeks.org/jvm-works-jvm-architecture/
Different components of the URL3-
Protocol:- https
Hostname:- www.google.co.in
Default port:- 443
Query:-
q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.6
53j0j7&sourceid=chrome&ie=UTF-8
Path:- /search
File:- /search?
q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.6
53j0j7&sourceid=chrome&ie=UTF-8
Reference:- q=geeks+for+geeks+java
INET ADDRESS CLASS
The java.net.InetAddress class provides methods to get the IP address
of any hostname. An IP address is represented by 32-bit or 128-bit unsigned
number. InetAddress can handle both IPv4 and IPv6 addresses.
There are 2 types of addresses :
Methods
main(String[] args)
throws UnknownHostException
{
InetAddress address1 = InetAddress.getLocalHost();
System.out.println("InetAddress of Local Host : " + address1);
InetAddress address2 = InetAddress.getByName("45.22.30.39");
System.out.println("InetAddress of Named Host : " + address2);
InetAddress address3[]= InetAddress.getAllByName("172.19.25.29");
for (int i = 0; i < address3.length; i++) {
System.out.println( "ALL InetAddresses of Named Host : "+ address3[i]);
}
byte IPAddress[] = { 125, 0, 0, 1 };
InetAddress address4 = InetAddress.getByAddress(IPAddress);
System.out.println( "InetAddresses of Host with specified IP Address : " +
address4);
byte[] IPAddress2= { 105, 22, (byte)223, (byte)186 };
Output:
PROGRAM:
import java.io.*;
import java.net.*;
import java.util.*;
class GFG {
public static void main(String[] args) throws UnknownHostException
{ InetAddress address1 = InetAddress.getByName("45.22.30.39");
InetAddress address2 = InetAddress.getByName("45.22.30.39");
InetAddress address = InetAddress.getByName("172.19.25.29");
System.out.println("Is Address-1 equals to Address-2? : " +
address1.equals(address2));
System.out.println( "Is Address-1 equals to Address-3? : "+
address1.equals(address3));
System.out.println("IP Address : "+ address1.getHostAddress());
System.out.println("Host Name for this IP Address : " +
address1.getHostName());
System.out.println("IP Address in bytes : " + address1.getAddress());
System.out.println("Is this Address Multicast? : " +
address1.isMulticastAddress());
System.out.println("Address in string form : " + address1.toString());
System.out.println( "Fully qualified domain name for this IP address : "+
address1.getCanonicalHostName());
System.out.println("Hashcode for this IP address : "+ address1.hashCode());
System.out.println("Is the InetAddress an unpredictable address? : "+
address1.isAnyLocalAddress());
} }
Output: