[go: up one dir, main page]

0% found this document useful (0 votes)
11 views14 pages

Unit 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

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 Java SE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.

JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a
specification from Sun micro systems that provides a standard abstraction(API or Protocol) for java applications
to communicate with various databases.

Components of JDBC
There are generally four main components of JDBC through which it can interact with a database. They are as
mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It provides two
packages as follows, which contain the java SE and Java EE platforms to exhibit WORA(write once run anywhere)
capabilities.
java.sql.*;
It also provides a standard to connect a database to a client application.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a
database. It is used to make a database-specific call to the database to process the user request.

3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC
Drivers.

4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the JDBC
method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native library
to access ODBC characteristics.

Architecture of JDBC
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests
from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin 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.
Advantage:
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 depend on the Database.
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 is used to register the driver class. This method is
used to dynamically load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

example to register the OracleDriver class

Here, Java program is loading oracle driver to establish database connection.

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","system","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


public Statement createStatement()throws SQLException

Example to create the statement object


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


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


public void close()throws SQLException
Merging data from multiple tables:
Join is a join that provides the facility to connect two tables are merged with each other according to a field that is common and
creates a new virtual table.

 NATURAL JOIN: It is a type of join that retrieves data within specified tables to a specific field that is matched.
 NATURAL LEFT JOIN: In this operation, both tables are merged with each other according to common fields but the priority
is given to the first table in the database.
 NATURAL RIGHT JOIN: It also the same as Natural left join but it retrieves the data from the second table in the database.

MySQL tables that are used in code:


First table

CREATE TABLE studentsdetails ( `id` int(6) unsigned NOT NULL,`Name`


varchar(50) NOT NULL, `caste` varchar(10) NOT NULL, `NeetMarks`
int(11) NOT NULL, `gender` varchar(10) DEFAULT NULL, PRIMARY KEY
(`id`))

Second table

CREATE TABLE `studentspersonaldetails` ( `id` int(6) unsigned NOT


NULL AUTO_INCREMENT, `Name` varchar(30) NOT NULL, `Address`
varchar(30) NOT NULL, `email` varchar(50) DEFAULT NULL, `reg_date`
timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE
current_timestamp(), PRIMARY KEY (`id`))

Merging table:

SELECT * FROM " + "studentsdetails" + " NATURAL JOIN " +


"studentspersonaldetails"
Java Database Connectivity with Oracle

To connect java application with the oracle database, we need to follow 5 following steps. In this example, we are
using Oracle 10g as the database. So we need to know following information 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:xe where 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 information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.

Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL query to create a
table.

create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and oracle are the username and 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);}

} }
1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter. In case of
servlet you need to write:

1. PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.

Example of out implicit object

In this example we are simply displaying date and time.

index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>

Output
Java Bean:
A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes −
 It provides a default, no-argument constructor.
 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.

Why use JavaBean?

It is a reusable software component. A bean encapsulates many objects into one object
so that we can access this object from multiple places. Moreover, it provides easy
maintenance.

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.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features


are accessed through two methods in the JavaBean's implementation class:

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.

Setter and Getter Methods in Java


Setter and Getter Methods in Java properties are mentioned below:

Properties for setter methods:


1. It should be public in nature.
2. The return type a should be void.
3. The setter method should be prefixed with the set.
4. It should take some argument i.e. it should not be a no-arg method.
Properties for getter methods:
1. It should be public in nature.
2. The return type should not be void i.e. according to our requirement, return type we
have to give the return type.
3. The getter method should be prefixed with get.
4. It should not take any argument.

Advantages of JavaBean

The following are the advantages of JavaBean:

o The JavaBean properties and methods can be exposed to another application.


o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead to
the boilerplate code.

Simple example of JavaBean class


//Employee.java

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;
}
}
How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

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

Types of EJB

Types of Enterprise Java Beans


There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be invoked by local,
remote or webservice client. There are two types of session beans:
(i) Stateful session bean and
(ii) (ii) Stateless session bean.

(i) Stateful Session bean :


Stateful session bean performs business task with the help of a state. Stateful
session bean can be used to access various method calls by storing the information
in an instance variable. Some of the applications require information to be stored
across separate method calls. In a shopping site, the items chosen by a customer
must be stored as data is an example of stateful session bean.

(ii) Stateless Session bean :


Stateless session bean implement business logic without having a persistent
storage mechanism, such as a state or database and can used shared data.
Stateless session bean can be used in situations where information is not required
to used across call methods.

2. Message Driven Bean: Like Session Bean, it contains the business logic but it is
invoked by passing message.

3. Entity Bean: It summarizes the state that can be remained in the database. It is
deprecated. Now, it is replaced with JPA (Java Persistent API). There are two types of
entity bean:

(i) Bean Managed Persistence :


In a bean managed persistence type of entity bean, the programmer has to write the
code for database calls. It persists across multiple sessions and multiple clients.
(ii) Container Managed Persistence :
Container managed persistence are enterprise bean that persists across database.
In container managed persistence the container take care of database calls.

You might also like