Unit 1-JDBC
Unit 1-JDBC
Unit 1-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.
We can use JDBC API to handle database using Java program and can perform the following
activities:
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)
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
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.
e.g.
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp1","root","");
e.g.
pst=con.prepareStatement(s);
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.
e.g. con.close();
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();
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");
}
}
}
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();
}}
Connection con;
PreparedStatement pst;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root",
"");
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:
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 ");
con.close();
}}
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.
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
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.
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
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with 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.
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 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.