0% found this document useful (0 votes)
28 views18 pages

UNIT-III Final

The document discusses JDBC (Java Database Connectivity) which allows Java applications to connect and interact with databases. It describes the key components of JDBC including the DriverManager class which manages database drivers, Connection objects for communicating with the database, Statement objects for executing SQL queries, and ResultSet objects which hold the data returned from queries. The document also outlines the different types of JDBC drivers including JDBC-ODBC bridge drivers, native-API drivers, network protocol drivers, and thin drivers.

Uploaded by

moaz.sheikh11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views18 pages

UNIT-III Final

The document discusses JDBC (Java Database Connectivity) which allows Java applications to connect and interact with databases. It describes the key components of JDBC including the DriverManager class which manages database drivers, Connection objects for communicating with the database, Statement objects for executing SQL queries, and ResultSet objects which hold the data returned from queries. The document also outlines the different types of JDBC drivers including JDBC-ODBC bridge drivers, native-API drivers, network protocol drivers, and thin drivers.

Uploaded by

moaz.sheikh11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT-III

JDBC(Java Data Base Connectivity)


Jdbc:

 JDBC stands for Java Database Connectivity which allows developers to connect, query and
update a database using the Structured Query Language(SQL).
 It is java API that defines interfaces and classes for database connection.
 JDBC allows to send SQL to any RDBMS. Thus it allows database access by embedding SQL
statement with java code.
 In short JDBC helps the programmers to write java applications that manage these three
programming activities:
 Connect to a datasource, like a database.
 Send queries and update statements to the database.
 Retrieve and process the results received from the database in answer to your
query.

JDBC architecture
Que:
1. Write a short note on JDBC Architecture.
2. Write a brief note on Three-Tier Database Design.
3. Explain general architecture of JDBC.
4. Explain JDBC architecture.
Ans:

 The JDBC API supports both two-tier and three-tier processing models for database access but
in general,:
 JDBC Architecture consists of two layers −

 JDBC API:

 This provides the application-to-JDBC Manager connection.


 The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
 JDBC Driver API:
 This supports the JDBC Manager-to-Driver Connection.
 The JDBC driver manager ensures that the correct driver is used to access each data source.
 The driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Two-Tier and Three Tier Architecture

JDBC API supports two model for database access

1) Two -tier model


 The two-tier architecture is based on Client Server architecture. The direct communication takes
place between client and server. There is no intermediate between client and server.
 In the two-tier model, a Java applet or application communicates directly to the data source.
where the user’s machine acts as a client and the machine having the data source running acts as
the server.
 The JDBC driver enables communication between the application and the data source.
 When a user sends a query to the data source, the answers for those queries are sent back to the
user in the form of results.
 The data source may not always be a single machine located at a single place. It can be located
on a different machine on a network to which a user is connected.
 The Two-tier architecture is divided into two parts:

1. Client Application (Client Tier)


2. Database (Data Tier)
Advantage
 Maintenance and understanding is easier.
Disadvantage
 This model gives poor performance when there are a large number of users. It can’t process
request of two user at a time.

2) Three- tier model


 Three-tier architecture typically comprises a Client tier, a business tier, and a data tier.
 In the three-tier model, client request is sent to a "Business tier/ middle tier". Middle tier
forward request the to the data source.
 The data source processes the request and sends the results back to the middle tier, which then
sends them to the user.
 Three layers in the three tier architecture are as follows:
1. Client Application (Client Tier)
2. Business Tier (Middle Tier)
3. Database (Data Tier)

1. Client Tier:

 It represents Web browser, a Java or other application, Applet etc.


 The client tier makes requests to the Web server who will be serving the request by either
returning static content if it is present in the Web server or forwards the request to either
Servlet or JSP in the application server for either static or dynamic content.

2. Business Tier:

 This tier contains the business logic like validation of data, calculations, data processing
etc. So, it provides the business services.
 This acts as an interface between Client layer and Data Access Layer.
 This layer is also called the intermediary layer helps to make communication faster between
client and data layer.
 The benefit of having a centralized business tier is that same business logic can support
different types of clients.

3. Data Tier:

 This layer is the external resource such as a database, ERP system, Mainframe system etc.
responsible for storing the data.

Advantages:
1. Enhanced scalability:

 due to distributed deployment of application servers,same business logic can support


different types of clients.

2.Data Integrity and Security:


1. It is improved. This type of model prevents direct interaction of the client with the
database server thereby reducing data corruption and unauthorized access of data.

Disadvantages:
1. Increase Complexity/Effort

Advantages and Disadvantage of JDBC

Que:
1. List advantages of using JDBC API?
2. Explain advantages and disadvantages of JDBC.
3. List out advantages of JDBC.
Ans:

Advantages

1. Provide Existing Enterprise Data


 Businesses can continue to use their installed databases and access information even if it is
stored on different database management system.
2. Simplified Enterprise Development
 The combination of the Java API and the JDBC API makes application development easy and
cost effective.
3. Zero Configuration for Network Computers
 No configuration is required on the client side.
 Driver is written in the Java, so all the information needed to make a connection is completely
defined by the JDBC URL.
4. No Installation
 A pure JDBC technology-based driver does not require special installation.
5. Database Connection Identified by URL
 The JDBC API includes a way to identify and connect to a data source, using a DataSource
object. This makes code even more portable and easier to maintain.

Disadvantage

1) Correct drivers need to be deployed for each type of database.


2) JDBC is not good for big applications.
3) Programmer must hardcode the Transactions and concurrency code in the application.
4) Handling the JDBC connections and properly closing the connection is also a big issue.

JDBC API Components


Que:
1. List JDBC API Components. Explain in brief.
2. Give the use of following classes: i. DriverManager. ii. Connection
3. What are the JDBC API components?
4. What is the role of JDBC DriverManager class in Java?
Ans:

 The JDBC API provides the following interfaces and classes

DriverManager:

 The JDBC DriverManager class manages a list of database drivers.


 Matches connection requests from the java application with the proper database driver using
communication sub protocol.
 The first driver that recognizes a certain subprotocol under JDBC will be used to establish a
database Connection
Driver:
 A driver is Java class, usually supplied by the database vendor, which implements the
java.sql.Driver interface.
 Primary function of the driver is to connect to a database and return a java.sql.connection
object.
 Drivers are not called directly by application programs.
 Instead, we use a DriverManager object, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.

Connection:

 This interface have all methods for contacting a database.


 All communication with database is through connection object only.
 A connection object is created by a call to either DriverManager.getConnection() or
DataSource.getConnection().

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.
 A statement is created with Connection.createStatement().

ResultSet:

 These objects hold data retrieved from a database after you execute an SQL query using
Statement objects.
 It acts as an iterator to allow you to move through its data.

SQLException:

 This class handles any errors that occur in a database application.

JDBC Drivers
Que:
1. List out types of JDBC drivers.
2. List JDBC Drivers. Explain JDBC-Net Pure Java Drivers (Type-3)
3. List JDBC Drivers. Explain JDBC-To-ODBC Bridge Driver (Type-1)
4. Discuss all types of JDBC Drivers.
5. List different categories of JDBC driver explain any one.
6. List out types of JDBC drivers. Explain any one type of driver in detail.
Ans:

 JDBC Driver is a software component that enables java application to interact with the
database.
 There are 4 types of JDBC drivers:
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)

1) Type –1 or 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.
 In this driver the database statements are converted to JDBC statements.
 JDBC statement calls the ODBC by using JDBC-ODBC bridge and finally query is
executed.
 This driver is platform dependent as it makes use of ODBC which is platform dependent.
 This is now discouraged because of thin driver.

Advantages:
 Easy to use.
 Can be easily connected to any database.

Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC
function calls.
 The ODBC driver needs to be installed on the client machine.

2 ) Type-2 or Native-API driver


 This driver is not written entirely in java.
 It uses Java Native library to make function calls to local database API.
 This driver convert JDBC call to driver specific call for database such as
SQL,ORACLE etc.
 It requires some native code to call vendor-specific API functions.
 It is faster than type-1 but like type-1 it requires native database client libraries to
installed and configured on client Machine.

Advantage:
 Performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.

3) Type-3 or Network Protocol driver:


 It uses middle –tier between calling program and the database.
 The middle tier converts JDBC calls directly or indirectly to vendor specific
database protocol.
 Database request pass through the network to middle-tier server. The middle tier
then translate request to database.
 Middle tier can use Type-1,Type-2 or Type-4 Drivers.
Advantage:
 No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.

4)Type-4 or 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.
 It is database specific if database change we have to deploy corresponding type-4 driver.

Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
Disadvantage:
 Drivers depend on the Database.

Steps to Get Database connection in a java program.


Que:
1. What is JDBC Connection? Explain steps to get Database connection using a java program
2. Write Steps to connect to the database in java.
3. Explain steps to get Database connection in a java program.
Ans:
 There are 5 steps to connect any java application with the database in java using JDBC. They
are as follows:
 Register the driver class
 Creating connection
 Creating statement
 Executing queries
 Closing connection

1. Register the driver class:

 The forName() method of Class 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 Mysql driver class:
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:

public static Connection getConnection(String url,String name,String password)


throws SQLException
 Example to establish connection with the mysql database:
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/database","username","password");
3. Create the Statement object:
 The createStatement() method of Connection class 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:

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

 The executeUpdate() method of Statement interface is used to perform insert,update and


delete operation into database.
 Syntax of executeUpdate() method:

public void executeUpdate(String sql)throws SQLException

 Example:

stmt.executeUpdate("insert into emp values(1,’abc’)");

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


 Example to close connection
con.close();
Steps to develop a JDBC application with proper example

Que:
1.Write the steps to develop a JDBC application with proper example
Ans:

 connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.

 In this example we are using MySql as the database. So we need to know following
informations for

1.Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

2. Connection URL: The connection URL for the mysql database


is jdbc:mysql://localhost:3306/test

 Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is
running, we may also use IP address, 3306 is the port number and test is the database name.
We may use any database, in such case, you need to replace the test with your database name.

Username: The default username for the mysql database is root.

Password: Password is given by the user at the time of installing the mysql database.
In this example, we are going to use “ ”(blank)as the password.

 Let's first create a table in the mysql database, but before creating table, we need to create
database first.

create database test


use sonoo;
create table emp(id int(10),name varchar(40));

 Example :

In this example, test is the database name, root is the username and password is blank.

import java.sql.*;
public class dbconnect {

public static void main(String[] args) {


try
{
System.out.println("hello");

Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");

Statement st=c.createStatement();
ResultSetrs=st.executeQuery("select * from emp");

while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

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

}
The above example will fetch all the records of emp table

JDBC Prepared Statement

Que:
1. Explain in brief: JDBC Prepared Statement
Ans:
 JDBC PreparedStatement can be used when you plan to use the same SQL statement many
times. It is used to handle precompiled query.
 If we want to execute same query with different values for more than one time then
precompiled queries will reduce the number of compilations

 It is used to execute parameterized query.

 Syntax of parameterized query:

String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

 Example:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","o
racle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101); //1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

Fetch Records from Database

Que:
1. Develop a JDBC application that uses any JDBC driver to fetch record. (Assume suitable
database)
Ans:

import java.sql.*;
public class dbconnect {

public static void main(String[] args) {


try
{

System.out.println("hello");

Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");

Statement st=c.createStatement();
ResultSetrs=st.executeQuery("select * from emp");

while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

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

Insert Record into Database


Que:
1. Develop a JDBC application that uses any JDBC driver to insert a record. (Assume suitable
database)
Ans:

import java.sql.*;
public class dbconnectds {

public static void main(String[] args) {


try
{
System.out.println("hello");

Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");

Statement st=c.createStatement();
String str="insert into emp VALUES(30,'PR')";
st.executeUpdate(str);
}
catch(Exception e)
{
System.out.println(e);
}

}
}

Update Record of Database


Que:
1. Develop a JDBC application that uses any JDBC driver to update a record. (Assume suitable
database)
Ans:
import java.sql.*;
public class dbconnectds {

public static void main(String[] args) {


try
{// TODO Auto-generated method stub

System.out.println("hello");
Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","");

Statement st=c.createStatement();
String str="update emp set eid=40 where eid=30";
st.executeUpdate(str);
ResultSet rs=st.executeQuery("select * from emp");
}
catch(Exception e)
{
System.out.println(e);
}

}
}
Delete Record from Database
Que:
1. Develop a JDBC application that uses any JDBC driver to delete a record. (Assume suitable
database)
Ans:
import java.sql.*;

public class dbconnectds {

public static void main(String[] args) {

try

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

Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");

Statement st=c.createStatement();

String str="delete from emp where eid=40";

st.executeUpdate(str);

catch(Exception e)

System.out.println(e);

}}}
Questions (Asked in GTU):
1. CRUD operations
2. List four common JDBC exceptions.
3. Explain different types of ResultSet in JDBC.
4. Give full name : JDBC, AWT
5. Which package is used to perform almost all JDBC operations?
6. Which package is used for JDBC application.
7. Write a program using servlets to reading database and displaying them.
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.

ResultSet.TYPE_SCROLL_INSENSITIV The cursor can scroll forward and backward, and the
E result set is not sensitive to changes made by others
to the database that occur after the result set was
created.

ResultSet.TYPE_SCROLL_SENSITIVE The cursor can scroll forward and backward, and the
result set is sensitive to changes made by others to
the database that occur after the result set was
created.

Common JDBC Exceptions

java.sql.SQLException This is the base exception class for JDBC exceptions.


java.sql.BatchUpdateException This exception is thrown when Batch operation fails, but it depends
on the JDBC driver whether they throw this exception or the base
SQLException.

java.sql.SQLWarning For warning messages in SQL operations.

java.sql.DataTruncation when a data values is unexpectedly truncated for reasons other than
its having exceeded MaxFieldSize.

List of JDBC Driver and Database URL


RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Drive jdbc:db2:hostname:port


r Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName

MS-ACCESS Sun.jdbc.odbc.JdbcOdbcDriver jdbc:odbc:databasename

You might also like