JDBC Unit3
JDBC Unit3
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database.
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
JDBC Implementation
JDBC (Java Database Connectivity) is a Java API that enables Java programs to
interact with databases. It provides a standard interface for accessing relational
databases from Java programs..
Import JDBC Packages: You need to import the necessary JDBC packages. These typically include
java.sql and the database-specific JDBC driver packages.
import java.sql.*;
Load the JDBC Driver: Load the JDBC driver for your particular database. This involves using
Class.forName() with the appropriate driver class name. Different databases have different driver
class names.
Class.forName("com.mysql.cj.jdbc.Driver");
Establish a Connection: Connect to the database using DriverManager.getConnection(). You need
to provide the database URL, username, and password.
Create a Statement: Create a Statement object using the createStatement() method of the
Connection object. This statement object is used to execute SQL queries.
Execute SQL Queries: You can execute SQL queries using the executeQuery() method for SELECT
queries or executeUpdate() for INSERT, UPDATE, DELETE queries.
Process the Results: If you executed a SELECT query, you can iterate over the ResultSet object to
retrieve the results.
while (resultSet.next()) {
Close the Connection: Finally, close the ResultSet, Statement, and Connection objects to release
database resources.
resultSet.close();
statement.close();
connection.close();
Program:
import java.sql.*;
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Execute a query
resultSet = statement.executeQuery("SELECT * FROM my_table");
Output
ID: 1, Name: John
ID: 2, Name: Alice
ID: 3, Name: Bob
The first thing you need to do before you can open a JDBC connection to a database is to load the
JDBC driver for the database.
Class.forName("driverClassName");
Each JDBC driver has a primary driver class that initializes the driver when it is loaded. For instance,
to load the H2Database driver, you write this:
Class.forName("org.h2.Driver");
The first method variant only takes a URL to the database as parameter. This is how
calling getConnection() only with the URL as parameter looks:
Connection connection =
DriverManager.getConnection(url);
Connection connection =
DriverManager.getConnection(url, user, password);
Open Connection With URL and Properties
Connection connection =
DriverManager.getConnection(url, properties);
The Properties object is used to pass special properties the database needs when opening the
connection
Once you are done using the database connection you should close it. This
is done by calling the Connection.close() method, like this:
connection.close();
statements
The statement interface is used to create SQL basic statements in Java it
provides methods to execute queries with the database. There are different
types of statements that are used in JDBC as follows:
Create Statement
Prepared Statement
Callable Statement
Syntax:
Statement statement = connection.createStatement();
Implementation: Once the Statement object is created, there are three ways
to execute it.
Remember to close these statement objects and release resources after you
finish using them to avoid memory leaks.
resultSet.close();
statement.close(); // or preparedStatement.close(); or
callableStatement.close();
ResultSet
The SQL statements that read data from a database query, return the data in a
result set. The SELECT statement is the standard way to select rows from a
database and view them in a result set. The java.sql.ResultSet interface represents
the result set of a database query.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
The cursor can scroll forward and backward, and the result set is
ResultSet.TYPE_SCROLL_INSENSITIVE
by others to the database that occur after the result set was crea
The cursor can scroll forward and backward, and the result set is
ResultSet.TYPE_SCROLL_SENSITIVE.
others to the database that occur after the result set was create
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
try {
Statement stmt =
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}
There are several methods in the ResultSet interface that involve moving the cursor,
including −
The ResultSet interface contains dozens of methods for getting the data of the current row.
Methods & Description
3. Execute SQL Queries: Execute SQL queries using the created statement objects.
4. Process Results (if any): If the query returns results, process them.
5. Close Resources: Close the resources (such as ResultSet, Statement, and Connection)
properly to release database resources and prevent memory leaks.
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.
IP Address
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 2 32 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:
TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a
network via internet.
o TCP/IP helps in the process of addressing, transmitting, routing and
receiving the data packets over the internet.
o The two main protocols used in this communication model are:
1. TCP i.e. Transmission Control Protocol. TCP provides the way to
create a communication channel across the network. It also helps in
transmission of packets at sender end as well as receiver end.
2. IP i.e. Internet Protocol. IP provides the address to the nodes
connected on the internet. It uses a gateway computer to check
whether the IP address is correct and the message is forwarded
correctly or not.
It returns the instance of InetAdddress containing local host name and address.
Output:
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
URL(String spec)
Creates an instance of a URL from the given protocol, host, port number,
and file.
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 with the specified
handler within a given context.
Method Description
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
3. Flow Control and Congestion Control: TCP incorporates mechanisms for flow control
and congestion control to manage the rate of data transmission and prevent
network congestion.
4. Ordered Data Transfer: TCP guarantees that data sent from one end is received in
the same order by the other end.
TCP is suitable for applications that require reliable, error-free, and ordered delivery of data,
such as web browsing, email communication, file transfer (e.g., FTP), and database
communication.
4. Fast Transmission: UDP is faster than TCP since it does not have to wait for
acknowledgment or retransmission of lost data.
UDP is suitable for applications that prioritize speed and can tolerate some degree of packet
loss, such as real-time audio and video streaming, online gaming, DNS (Domain Name
System), and SNMP (Simple Network Management Protocol).
JAVA BEAN
What is JavaBeans?
JavaBeans is a portable, platform-independent model written in Java Programming
Language. Its components are referred to as beans.
In simple terms, JavaBeans are classes which encapsulate several objects into a
single object. It helps in accessing these object from multiple places. JavaBeans
contains several elements like Constructors, Getter/Setter Methods and much more.
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
javaBean Properties
A JavaBean property is a named feature that can be accessed by the user
of the object. The feature can be of any Java data type, containing the
classes that you define.
1. getPropertyName ()
For example, if the property name is firstName, the method name would
be getFirstName() to read that property. This method is called the
accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would
be setFirstName() to write that property. This method is called the
mutator.
Advantages of JavaBean
The following are the advantages of JavaBean:/p>
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
RMI
The RMI (Remote Method Invocation) is an API that provides a mechanism
to create distributed application in java. The RMI allows an object to
invoke methods on an object running in another JVM.
RMI uses stub and skeleton object for communication with the remote
object.
stub
The stub is an object, acts as a gateway for the client side. All the
outgoing requests are routed through it. It resides at the client side and
represents the remote object. When the caller invokes method on the stub
object, it does the following tasks:
skeleton
The skeleton is an object, acts as a gateway for the server side object. All
the incoming requests are routed through it. When the skeleton receives
the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler.
The rmic tool invokes the RMI compiler and creates stub and skeleton
objects.
1. rmic AdderRemote
1. rmiregistry 5000
In this example, we are binding the remote object by the name sonoo.
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}