0% found this document useful (0 votes)
8 views23 pages

A STUDY ON:-Interacting With Database Micro Project by Devansh Deshmukh

The document is a micro project report by Devansh Deshmukh on 'Interacting with Database' as part of the Advance Java Programming course for the academic year 2024-25. It covers key concepts such as JDBC and ODBC, their differences, and the process of connecting to a database using JDBC, including driver types and architecture. The report also includes practical examples and discusses advantages and disadvantages of various JDBC drivers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views23 pages

A STUDY ON:-Interacting With Database Micro Project by Devansh Deshmukh

The document is a micro project report by Devansh Deshmukh on 'Interacting with Database' as part of the Advance Java Programming course for the academic year 2024-25. It covers key concepts such as JDBC and ODBC, their differences, and the process of connecting to a database using JDBC, including driver types and architecture. The report also includes practical examples and discusses advantages and disadvantages of various JDBC drivers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Subject Name: Advance Java Programming (22517) Academic Year: 2024-25

Course Name: Computer Engineering Semester: FIFTH

A STUDY ON:- Interacting with Database


MICRO PROJECT

By Devansh Deshmukh

Sr.No. Roll No Name of Student Enrollment No. Seat No.

1 48 Devansh Deshmukh 2209350168

Under the guidance of


Miss. Ashwini Dhage

Third year of Diploma program in Engineering and Technology of Maharashtra State board of Technical
Education, Mumbai.
AT
SHIVAJIRAO S. JONDHLE POLYTECHNIC ASANGAON

-1-
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

This is Certify that Mr. Devansh R Deshmukh, Roll no. 48 in fifth semester of Computer Engineering Diploma
program in Engineering and Technology At 0935- SHIVAJIRAO S. JONDHLE POLYTECHNIC has completed the
Micro Project Satisfactorily in subject Advance Java Programming (22517) in the academic year 2024 - 2025 as
per the MSBTE Prescribed curriculum of ‘I’ Scheme.

Place: Asangaon Enrollment no. 2209350168

Date : / / 2024 Exam seat no.

Subject Teacher Head of department Principal

Seal of Institute

-2-
INDEX

Sr.No. Content Pg.No.

1 Introduction to JDBC and 4


ODBC

2 JDBC vs ODBC 7

3 Connecting to a Database 8

4 JDBC Architecture 16

5 Types of JDBC Drivers 18

7 Advantages & Disadvantages 20


Of Types of JDBC Drivers

8 Conclusion 22

9 References 22

-3-
Introduction to JDBC and ODBC

JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) are both APIs
(Application Programming Interfaces) that facilitate communication between Java
applications and databases. They provide a standard way for developers to interact with
various database systems, eliminating the need for specific database-dependent code.
JDBC is Java-specific, designed to work seamlessly with the Java programming language.
ODBC, on the other hand, is platform-independent, allowing various programming languages
to access databases. Both JDBC and ODBC utilize drivers to translate requests from the
application to the database, enabling data access and manipulation.

1. ODBC (Open Database Connectivity)

ODBC is a standard API (Application Programming Interface) for accessing database


management systems (DBMS). It was developed by Microsoft in the early 1990s to allow
applications to communicate with databases using SQL, regardless of the underlying
database system.

 Platform: Primarily used in C/C++ and other non-Java environments.


 Main Goal: Provide a universal data access interface that abstracts the underlying
database system.

 Key Features:
o Allows access to a variety of database systems (Oracle, SQL Server, MySQL, etc.)
using a common set of functions.
o Uses drivers that act as a bridge between the application and the database.
o Supports different types of databases through the installation of respective
ODBC drivers.

-4-
 How it Works:
1. The application uses ODBC functions to send SQL queries.
2. The ODBC driver translates these SQL queries into a form that the database
understands.
3. The results are returned to the application via the ODBC interface.

 Advantages:
o Database-agnostic: Works with many databases via the installation of the
appropriate drivers.
o Platform-independent in terms of database communication.

 Disadvantages:
o ODBC is mostly used in Windows environments and can be difficult to configure.
o Performance can be affected depending on the driver used.

2. JDBC (Java Database Connectivity)

JDBC is an API specifically designed for Java applications to interact with databases. It enables
Java programs to connect to relational databases, send SQL queries, and process the results.

 Platform: Used in Java environments.


 Main Goal: Allow Java applications to communicate with databases in a standardized
and consistent way.

-5-
 Key Features:

o JDBC allows Java applications to access a variety of databases using SQL queries.
o JDBC provides both low-level and high-level interfaces to perform database
operations.
o Unlike ODBC, JDBC is native to Java, meaning no additional platform-specific
libraries are needed.

 How it Works:

1. The Java program loads the database driver (which is specific to the type of database).
2. It establishes a connection to the database using the DriverManager.getConnection()
method.
3. SQL queries are executed using the Statement object.
4. The results are processed by iterating over the ResultSet object.
5. Once done, the connection is closed.

 Advantages:

o Platform-independent: As part of Java, it works on any platform that supports


Java.
o Simpler to configure than ODBC (no need for extra installation or configuration
of drivers).
o Supports connection pooling, batch processing, and transaction management,
making it more powerful for enterprise-level applications.
 Disadvantages:
o JDBC can be slower than ODBC for certain operations because it is Java-based
and adds an additional layer between the application and the database.

-6-
JDBC vs ODBC

Feature JDBC ODBC


Java-Specific Platform-independent
Language

Java-based Platform-Specific
Driver

Based on Java APIs Based on C APIs


Architecture

Generally Faster Can be slower due to


Performance additional layers.

Primarily used for Java Used for various


Usage Application programming languages.

As evident from the table, JDBC and ODBC differ in their scope, drivers, architecture,
performance, and intended use cases. JDBC is specifically designed for Java applications,
while ODBC offers a broader reach to various languages. Choosing between JDBC and ODBC
depends on the specific programming language and the desired level of performance. JDBC is
usually favoured for Java applications due to its performance and ease of use within the Java
environment.

-7-
Connecting to Database

To interact with a database from a program, you need to establish a connection between
your application and the database system. This connection allows you to send SQL queries,
retrieve results, and manipulate the data stored in the database.
The process of connecting to a database typically involves several key steps, including loading
the database driver, establishing the connection, and managing the connection effectively
during use.

Key Steps in Database Connectivity


1. Load the Database Driver
2. Establish a Connection to the Database
3. Create and Execute SQL Statements
4. Process the Results
5. Close the Connection
Below is an explanation of each step, focusing on JDBC (Java Database Connectivity) for Java
applications, which is one of the most commonly used approaches for connecting to a
database.

-8-
1. Load the Database Driver (JDBC)
Before connecting to a database, you must load the database driver, which is responsible for
translating Java calls into database-specific calls.
In JDBC, a database driver is usually provided by the database vendor (e.g., Oracle, MySQL,
PostgreSQL). JDBC drivers can be divided into four types based on their architecture:
 Type 1: JDBC-ODBC bridge driver (outdated, not recommended).
 Type 2: Native-API driver (uses database-specific client libraries).
 Type 3: Network Protocol driver (uses a middleware server for communication).
 Type 4: Thin driver (pure Java driver, most commonly used today).
To load a driver, you typically use Class.forName() in Java to dynamically load the driver class.
Example (MySQL Driver):
java
Copy code
try {
// Load MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

-9-
2. Establish a Connection to the Database
Once the driver is loaded, you can establish a connection to the database using
DriverManager.getConnection() or a DataSource object (for more advanced connection
pooling). The getConnection() method takes a URL, a username, and a password for the
database.
Example of JDBC Connection:
For a MySQL database, the URL format is:
php
Copy code
jdbc:mysql://<hostname>:<port>/<database_name>
Example code to establish a connection:
java
Copy code
import java.sql.*;

public class DatabaseConnection {


public static void main(String[] args) {
Connection conn = null;
try {
// Load the MySQL driver (Class.forName() is optional in modern JDBC)
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
conn = DriverManager.getConnection(url, username, password);
System.out.println("Connection successful!");
-10-
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
// Close the connection when done
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
 URL: The connection URL tells the JDBC driver which database to connect to and
where it is located (hostname and port).
 Username and Password: These credentials are used to authenticate the user with the
database system.

-11-
3. Create and Execute SQL Statements
Once you have a connection, you can create SQL statements (queries, inserts, updates,
deletes, etc.) using the Statement, PreparedStatement, or CallableStatement objects in JDBC.
 Statement: For executing simple SQL queries.
 PreparedStatement: For executing SQL queries with parameters (precompiled for
efficiency).
 CallableStatement: For executing stored procedures.
Example of Executing a Simple Query:
java
Copy code
Statement stmt = null;
ResultSet rs = null;

try {
// Create a Statement object
stmt = conn.createStatement();

// Execute a query and retrieve results


String sql = "SELECT id, name FROM users";
rs = stmt.executeQuery(sql);

// Process the result set


while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
-12-
e.printStackTrace();
} finally {
// Close the Statement and ResultSet
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
 executeQuery() is used for SELECT queries that return a result set.
 executeUpdate() is used for INSERT, UPDATE, DELETE, or any DDL operations (like
CREATE TABLE).

4. Process the Results


When executing a SELECT query, the results are stored in a ResultSet. A ResultSet represents
the data returned by the query and allows you to iterate through the rows and columns.
 rs.next(): Moves the cursor to the next row.
 rs.getInt(), rs.getString(), etc.: Retrieve data from the current row using the column
index or column name.

-13-
5. Close the Connection
Always close the database resources after use to avoid memory leaks or connection pool
exhaustion. This includes:
 ResultSet
 Statement
 Connection
A good practice is to use a finally block to ensure resources are always closed, even if an
exception occurs.
Example:
java
Copy code
try {
// Use the resources (e.g., Statement, ResultSet)
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

-14-
Connection Pooling (Advanced)
In a production environment, managing database connections can become inefficient if each
request opens a new connection. Connection pooling helps manage connections efficiently
by reusing connections from a pool rather than opening new ones for every database
interaction.
 Why use connection pooling?
o Reduces the overhead of opening and closing connections.
o Improves performance and scalability of applications.
Popular libraries for connection pooling include Apache Commons DBCP, HikariCP, and C3P0.

Common Issues When Connecting to a Database


1. Driver not found: Ensure the correct JDBC driver is on the classpath.
2. Incorrect database URL: The URL format must be correct, including the hostname, port,
and database name.
3. Authentication failure: Double-check the username and password.
4. Connection timeout: This may occur if the database server is unreachable or the
connection settings are incorrect.
5. SQL Exceptions: Ensure the SQL queries are correct, and handle SQL exceptions
properly.

-15-
JDBC Architecture

JDBC architecture comprises several key components that work together to enable database
interaction:
 JDBC API: Provides a set of interfaces and classes that define the standard for
interacting with databases. This API serves as the foundation for communicating with
various database systems.
 JDBC Driver Manager: Acts as a central manager responsible for loading and managing
JDBC drivers. It handles the task of finding and connecting to the appropriate driver for
the specific database.
 JDBC Driver: A software component that translates JDBC API calls into a database-
specific format. It acts as a bridge between the Java application and the database,
making the communication seamless. There are four types of JDBC drivers: Type 1
(JDBC-ODBC bridge), Type 2 (Native API partly Java), Type 3 (Network Protocol), and
Type 4 (Native Protocol Pure Java).
 Database: The actual database management system (DBMS) where the data is stored.
It can be any type of database like MySQL, Oracle, PostgreSQL, etc.
This architectural model ensures flexibility and portability for Java applications interacting
with databases. The separation of concerns between the JDBC API, driver manager, and
drivers allows for a standard, well-defined interaction process.

 Two Tier Database Design

A two-tier architecture refers to a system where the application is divided into two distinct
layers: the client tier and the database tier. In a two-tier design, the client directly interacts
with the database without the involvement of any intermediary layers (such as a middle-tier
application server).
-16-
 Three-Tier Database Driver

Three-tier architecture is a widely-used design pattern in software development that


separates the application into three distinct layers: the presentation tier, the logic tier, and
the data tier. Each tier has a specific responsibility, promoting modularity, scalability,
maintainability, and flexibility.
In a three-tier architecture, the client interacts with the presentation layer (the user
interface), which in turn communicates with the logic layer (where business logic is
processed). The logic layer communicates with the data tier (the database) to fetch, store,
and manipulate data. This separation of concerns makes the system more scalable and easier
to maintain.

-17-
Types of JDBC Drivers
JDBC drivers come in various types, each with its own advantages and disadvantages.
Understanding the types of drivers available is crucial for selecting the best option for your
specific project. These types include:
 JDBC-ODBC Bridge Driver (Type 1): Uses ODBC to communicate with databases. It
requires ODBC drivers to be installed on the system. This type is generally less efficient
and less preferred.

 Native API Partly Java Driver (Type 2): Combines Java code with database-specific
native libraries. This approach offers better performance but introduces platform-
specific dependencies. It might require native library installation on the system.

-18-
 Network Protocol Driver (Type 3): Communicates with a middle-tier server that then
interacts with the database. This type is typically used in multi-tier architectures and
offers flexibility for distributed environments.

 Native Protocol Pure Java Driver (Type 4): The most efficient and preferred type. It
communicates directly with the database using a pure Java implementation. It offers
the best performance and eliminates the need for platform-specific libraries.

Choosing the right driver type depends on factors such as performance requirements,
platform compatibility, and security considerations. Type 4 drivers are usually the most
efficient and preferred choice, offering a pure Java implementation and direct
communication with the database.

-19-
Advantages & Disadvantages of Types of JDBC Drivers

1. Type 1: JDBC-ODBC Bridge Driver


 Advantages:
o Database Independence: It can be used to connect to any database that has an
ODBC driver available.
o Ease of Setup: For small-scale applications, it is easy to configure because the
ODBC drivers are already available for most relational databases.
 Disadvantages:
o Performance Overhead: The use of ODBC as a bridge adds an additional layer of
communication, causing performance degradation, especially with large
datasets or high traffic.
o Platform Dependency: The ODBC driver is platform-dependent (i.e., it's
dependent on the operating system), making it difficult to port the application
across different platforms.

2. Type 2: Native-API Driver


 Advantages:
o Faster Performance: Because it communicates directly with the database using
the database’s native protocol, Type 2 drivers tend to have better performance
than the Type 1 JDBC-ODBC bridge.
o Database-Specific Features: Native-API drivers can take advantage of specific
features and optimizations of the database.
 Disadvantages:
o Platform Dependency: This driver is platform-dependent because it requires the
database's native client library to be installed, and those libraries may vary
across different operating systems.
o Limited Portability: Since it relies on the database’s proprietary client, this driver
is less portable. If you want to switch to a different DBMS, you may need to
replace the driver and adjust the application.

-20-
3. Type 3: Network Protocol Driver
 Advantages:
o Database Independence: The Type 3 driver is database-agnostic, as it
communicates with a middleware layer that can connect to different types of
databases.
o Platform Independence: Since the driver communicates through a network
protocol and does not depend on the native database libraries, it can work
across different platforms (cross-platform compatibility).
 Disadvantages:
o Performance Overhead: Since the driver communicates through a middleware
layer, the added hop can introduce performance overhead, particularly with
high latency or large-scale operations.
o Complexity: Requires an additional middleware layer, which can complicate the
system architecture, requiring extra configuration, monitoring, and
maintenance.

4. Type 4: Thin Driver (Pure Java Driver)


 Advantages:
o Performance: The Type 4 driver offers high performance because it
communicates directly with the database over a network using the database's
own protocol (no intermediary layers like ODBC, native API, or middleware).
o Platform Independence: Being written entirely in Java, Type 4 drivers are
platform-independent. They can run on any platform that supports Java, making
them highly portable.
 Disadvantages:
o Database-Specific: Unlike Type 3 drivers, Type 4 drivers are often database-
specific, meaning you need a separate driver for each type of database (e.g.,
MySQL, Oracle, SQL Server).
o Limited Support for Some Advanced Features: While it supports most basic
features of JDBC, there might be cases where the driver does not support all
advanced database features that may be present in Type 2 or Type 3 drivers
(depending on the database and driver implementation).
-21-
Conclusion

JDBC plays a crucial role in bridging the gap between Java applications and databases,
enabling seamless data access and manipulation. Understanding the fundamentals of JDBC,
ODBC, driver types, and connection processes empowers developers to build robust and
data-driven applications. To further your knowledge, you can explore online resources,
books, and tutorials specifically designed for JDBC.

References

 Oracle Java Tutorial: https://docs.oracle.com/javase/tutorial/jdbc/


 JDBC API Documentation:
https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html
 tutorialspoint.com: https://www.tutorialspoint.com/jdbc/
 Wikipedia
 Class Notes

-22-

You might also like