Unit 1-JDBC

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

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.

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.

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the 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).

We can use JDBC API to handle database using Java program and can perform the following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

What is API
API (Application programming interface) is a document that contains a 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 J
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)

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:

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.
o
Java Database Connectivity with 5 Steps

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

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to dynamicall
the driver class.

Syntax of forName() method

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

2. e.g.

Class.forName("com.mysql.jdbc.Driver");
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

e.g.

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp1","root","");

3) Create the Statement object


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

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

e.g.

pst=con.prepareStatement(s);

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This method re
the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

e.g. pst.executeUpdate();
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() meth
Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

e.g. con.close();

wap for insert data into database.

package swing;
import java.sql.*;
public class insertPrepared {
public static void main(String args[]){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","");
PreparedStatement stmt=con.prepareStatement("insert into emp values(?,?,?)");
stmt.setInt(1,109);//1 specifies the first parameter in the query
stmt.setString(2,"NAKSHU ");
stmt.setInt(3,80000);

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

con.close();

}catch(Exception e){ System.out.println(e);}


}
}
wap for update data into database .

package swing.newpackage;

import java.sql.*;
public class Update1 {
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
PreparedStatement stmt=con.prepareStatement("update emp set name=?
where id=?");
stmt.setString(1,"lawanya");//1 specifies the first parameter in the query i.e.
name
stmt.setInt(2,102);

int i=stmt.executeUpdate();
System.out.println(i+" records updated");
con.close();
}catch(Exception e)
{
System.out.println("not updated");

}
}
}

wap for delete data into database .

package swing.newpackage;

import java.sql.*;
public class FetchRecord {
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root",
"");
Statement stmt=con.createStatement();
int result=stmt.executeUpdate("delete from emp where id=102");
System.out.println(result+" records affected");
con.close();
}}

Connectivity of Login Form with database


Code :-

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

Connection con;

PreparedStatement pst;

try{

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root",
"");

String s = "insert into login(Name,Password) values


('"+t1.getText()+"','"+t2.getText()+"') " ;

pst=con.prepareStatement(s);

int i= pst.executeUpdate();

if(i>=1)

JOptionPane.showMessageDialog(null," Updated!!!!!!!!");

}catch(Exception e)

JOptionPane.showMessageDialog(null, e);

}
}

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.

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

Commonly used methods of ResultSet interface


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 is used to return the data of specified column
columnName): name of the current row as String.

Example of Scrollable ResultSet


package swing;
import java.sql.*;
public class display {
public static void main(String args[])throws Exception{

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root",
"");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.C
ONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp ");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

What is Java Networking?

Networking supplements a lot of power to simple programs. With networks, a single


program can regain information stored in millions of computers positioned anywhere
in the world. Java is the leading programming language composed from scratch with
networking in mind. Java Networking is a notion of combining two or more
computing devices together to share resources.
All the Java program communications over the network are done at the application
layer. The java.net package of the J2SE APIs comprises various classes and
interfaces that execute the low-level communication features, enabling the user to
formulate programs that focus on resolving the problem.

Common Network Protocols

As stated earlier, the java.net package of the Java programming language includes
various classes and interfaces that provide an easy-to-use means to access network
resources. Other than classes and interfaces, the java.net package also provides
support for the two well-known network protocols. These are:
1. Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol
allows secure communication between different applications. TCP is a
connection-oriented protocol which means that once a connection is established,
data can be transmitted in two directions. This protocol is typically used over the
Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in
methods to examine for errors and ensure the delivery of data in the order it was
sent, making it a complete protocol for transporting information like still images,
data files, and web pages.

2. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-


less protocol that allows data packets to be transmitted between different
applications. UDP is a simpler Internet protocol in which error-checking and
recovery services are not required. In UDP, there is no overhead for opening a
connection, maintaining a connection, or terminating a connection. In UDP, the
data is continuously sent to the recipient, whether they receive it or not.

Java Networking Terminology

In Java Networking, many terminologies are used frequently. These widely used
Java Networking Terminologies are given as follows:
1. IP Address – An IP address is a unique address that distinguishes a device on the
internet or a local network. IP stands for “Internet Protocol.” It comprises a set of
rules governing the format of data sent via the internet or local network. IP
Address is referred to as a logical address that can be modified. It is composed of
octets. The range of each octet varies from 0 to 255.
 Range of the IP Address – 0.0.0.0 to 255.255.255.255
 For Example – 192.168.0.1

2. Port Number – A port number is a method to recognize a particular process


connecting internet or other network information when it reaches a server. The
port number is used to identify different applications uniquely. The port number
behaves as a communication endpoint among applications. The port number is
correlated with the IP address for transmission and communication among two
applications. There are 65,535 port numbers, but not all are used every day.

3. Protocol – A network protocol is an organized set of commands that define how


data is transmitted between different devices in the same network. Network
protocols are the reason through which a user can easily communicate with
people all over the world and thus play a critical role in modern digital
communications. For Example – TCP, FTP, POP, etc.
4. MAC Address – MAC address stands for Media Access Control address. It is a
bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card).
It contains a 48 bit or 64-bit address, which is combined with the network
adapter. MAC address can be in hexadecimal composition. In simple words, a
MAC address is a unique number that is used to track a device in a network.

5. Socket – A socket is one endpoint of a two-way communication connection


between the two applications running on the network. The socket mechanism
presents a method of inter-process communication (IPC) by setting named
contact points between which the communication occurs. A socket is tied to a
port number so that the TCP layer can recognize the application to which the data
is intended to be sent.

6. Connection-oriented and connection-less protocol – In a connection-oriented service,


the user must establish a connection before starting the communication. When
the connection is established, the user can send the message or the information,
and after this, they can release the connection. However, In connectionless
protocol, the data is transported in one route from source to destination without
verifying that the destination is still there or not or if it is ready to receive the
message. Authentication is not needed in the connectionless protocol.
 Example of Connection-oriented Protocol – Transmission Control Protocol
(TCP)
1. DatagramSocket – The DatagramSocket class is a network socket that provides a
connection-less point for sending and receiving packets. Every packet sent from
a datagram socket is individually routed and delivered. It can further be practiced
for transmitting and accepting broadcast information. Datagram Sockets is Java’s
mechanism for providing network communication via UDP instead of TCP.

2. Proxy – A proxy is a changeless object and a kind of tool or method or program or


system, which serves to preserve the data of its users and computers. It behaves
like a wall between computers and internet users. A Proxy Object represents the
Proxy settings to be applied with a connection.

3. URL – The URL class in Java is the entry point to any available sources on the
internet. A Class URL describes a Uniform Resource Locator, which is a signal
to a “resource” on the World Wide Web. A source can denote a simple file or
directory, or it can indicate a more difficult object, such as a query to a database
or a search engine.

4. URLConnection – The URLConnection class in Java is an abstract class describing


a connection of a resource as defined by a similar URL. The URLConnection
class is used for assisting two distinct yet interrelated purposes. Firstly it
provides control on interaction with a server(especially an HTTP server) than a
URL class. Furthermore, with a URLConnection, a user can verify the header
transferred by the server and can react consequently. A user can also configure
header fields used in client requests using URLConnection.
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.

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

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

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.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Creating Server:

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.

1. ServerSocket ss=new ServerSocket(6666);


2. Socket s=ss.accept();//establishes connection and waits for the client

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.

1. Socket s=new Socket("localhost",6666);

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 hi I am sandhya");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

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.

You might also like