0% found this document useful (0 votes)
3 views

Chapter 6

Chapter 6 covers JDBC (Java Database Connectivity), a Java API for connecting applications to relational databases, enabling SQL execution and data manipulation. It explains the steps to establish a database connection, types of JDBC drivers, and the MVC model for project development. Key features include platform independence, various statement types for executing queries, and the importance of closing database resources to prevent memory leaks.

Uploaded by

singhmaanvi779
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 6

Chapter 6 covers JDBC (Java Database Connectivity), a Java API for connecting applications to relational databases, enabling SQL execution and data manipulation. It explains the steps to establish a database connection, types of JDBC drivers, and the MVC model for project development. Key features include platform independence, various statement types for executing queries, and the importance of closing database resources to prevent memory leaks.

Uploaded by

singhmaanvi779
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter 6 (UNIT 2)

JDBC (Java Database Connetivity)

(Database Connectivity, Type of drivers for connections, Connection Example, CRUD operations
using database, Configurig various type of drivers for java database connectivity, MVC Model for
project development, Sequences, dual Table, Datatype management in Java)
Database Connectivity

JDBC (Java Database Connectivity) is a Java-based API (Application Programming


Interface) that provides a standard interface for connecting Java applications with
relational databases. It allows Java programs to interact with databases, execute SQL
queries, and retrieve or update data.
Key Features of JDBC:
• Database Connectivity: Allows Java applications to connect seamlessly with
multiple relational databases.
• SQL Execution: Supports executing SQL queries, including SELECT, INSERT, UPDATE,
and DELETE operations.
• Result Processing: Enables retrieval and manipulation of data from the database.
• Platform Independence: Works across different database management systems
using JDBC drivers.
Why use JDBC over ODBC

Feature JDBC Architecture ODBC Architecture


Language-
Language
Java-specific API independent (C, C++,
Dependency
etc.)
Platform- Platform-dependent
Platform
independent (works (relies on native OS
Dependency
on any OS with JVM) libraries)
Driver Type Uses JDBC Drivers Uses ODBC Drivers
Faster (direct Java Slower (extra ODBC
Performance
integration) layer)
Recommended for Suitable for non-Java
Usage
Java applications applications
Less secure (relies on
More secure (runs
Security system
inside Java)
configurations)
Steps to Connect a Java Application with a Database
using JDBC
1. Importing Packages
2. Loading JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection
1. Importing Packages

The JDBC API is part of the java.sql package and provides various interfaces, classes, and
exceptions to facilitate database connectivity in Java applications.

import java.sql.*; // For standard JDBC operations


import java.math.*; // For handling Decimal and Integer values

The java.sql package contains essential classes and interfaces for database operations.

Interfaces:
CallableStatement, Connection, DatabaseMetaData, Statement, Driver,
PreparedStatement, ResultSet, ResultSetMetaData etc.
Classes:
Date, DriverManager, DriverPropertyInfo, Time, Timestamp, Types
Exceptions:
DataTruncation, SQLException, SQLWarning
2. Loading JDBC Drivers

Before a Java application can interact with a database, it needs to load the appropriate JDBC
driver. The driver acts as a bridge between the Java application and the database.

Methods to Load a JDBC Driver


1. Using Class.forName() (Explicit Loading - Pre JDBC 4.0)
Class.forName("com.mysql.cj.jdbc.Driver");
• This method dynamically loads the driver class into memory.
• It ensures that the driver is registered with DriverManager.
• Commonly used for MySQL, PostgreSQL, Oracle, and SQL Server drivers.

2. Automatic Loading (JDBC 4.0+)


• The driver is loaded automatically when DriverManager.getConnection() is called.
• No need to call Class.forName() explicitly

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");


2. Loading JDBC Driver Contd.

Driver Class Names for Common


Databases
Database JDBC Driver Class
MySQL com.mysql.cj.jdbc.Driver
PostgreSQL org.postgresql.Driver
Oracle oracle.jdbc.driver.OracleDriver
SQL Server com.microsoft.sqlserver.jdbc.SQLServerDriver
3. Opening a Connection to a Database

Once the JDBC driver is loaded, the next step is to establish a connection between the Java application and
the database using DriverManager.getConnection().

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");

Connection URL Format for Different Databases


Each database has its own JDBC connection URL format:

Database JDBC URL Format


MySQL jdbc:mysql://hostname:port/database_name
PostgreSQL jdbc:postgresql://hostname:port/database_name
Oracle jdbc:oracle:thin:@hostname:port:SID
SQL Server jdbc:sqlserver://hostname:port;databaseName=DB_NAME
3. Opening a Connection to a Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {


public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/mydatabase"; // JDBC URL
String user = "root"; // Database username
String password = "password"; // Database password

try {
// Establish connection
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Database connected successfully!");

// Close the connection


conn.close();
} catch (SQLException e) {
System.out.println("Database connection failed! " + e.getMessage());
}
}
}
4. Creating a Statement Object

Once a connection is established, the next step is to create a Statement object, which is used to
execute SQL queries SELECT, INSERT, UPDATE, DELETE) against the database.

Types of Statement Objects in JDBC


JDBC provides three types of statements to execute SQL queries:

Statement Type Description Use Case


Statement Used for simple SQL queries without parameters. Best for static queries.
PreparedStatement Precompiled SQL statement with parameters (?). Best for dynamic queries and security.
CallableStatement Used to call stored procedures in the database. Best for executing stored procedures.

We create a Statement object from a Connection using the createStatement() method. Always
close the Statement object after execution to free resources.

Statement stmt = conn.createStatement();


5. Executing a Query and Returning a Result Set Object

Once the Statement object is created, we can use it to execute SQL queries. The result of SELECT
queries is stored in a ResultSet object.

Methods to Execute Queries in JDBC


JDBC provides three methods in the Statement interface to execute SQL commands:

Method Return Type Use Case

executeQuery(String sql) ResultSet Used for SELECT queries (fetching data).

Used for INSERT, UPDATE, DELETE queries


executeUpdate(String sql) int (row count)
(modifying data).
Used for DDL (CREATE, ALTER, DROP) and
execute(String sql) boolean
multiple result sets.
5. Executing a Query and Returning a Result Set Object /CRUD
Operations

Example: Fetching Data from a Database Example: Updating a Record


//Execute SQL query String sql = "UPDATE users SET email='[email protected]' WHERE id=1";
String sql = "SELECT id, name, email FROM users"; int rowsAffected = stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(sql); System.out.println(rowsAffected + " row(s) updated.");

// Process the ResultSet


while (rs.next())
{
int id = rs.getInt("id"); // Fetch ID column Example: Creating a table in a database
String name = rs.getString("name"); // Fetch Name column
String email = rs.getString("email"); // Fetch Email column String sql = "CREATE TABLE Students (" + "ID INT PRIMARY KEY, " + "Name
VARCHAR(50), " + "Age INT)";
System.out.println("ID: " + id + ", Name: " + name + ", Email: " boolean result = stmt.execute(sql);
+ email); System.out.println("Table Created: " + !result);
}
6. Processing the Result Set
When executing a SELECT query using executeQuery(), the result is stored in a ResultSet object. The
ResultSet represents the data retrieved from the database and allows us to process it row by row.

Navigating Through the ResultSet


The ResultSet cursor starts before the first row. To process the data, we use the .next() method to move
the cursor forward.
Common ResultSet Methods
Method Description
rs.next() Moves the cursor to the next row (returns false when no more rows).
rs.getInt(columnLabel) Retrieves an integer from a column.
rs.getString(columnLabel) Retrieves a string from a column.
rs.getDouble(columnLabel) Retrieves a double value from a column.
rs.getDate(columnLabel) Retrieves a date from a column.
rs.getBoolean(columnLabel) Retrieves a boolean value from a column.
6. Processing the Result Set

Processing Different Data Types


Example: Handling Various Column Types
if (rs.next()) { // Moves the cursor to the first row
int userId = rs.getInt("id");
String username = rs.getString("username");
double balance = rs.getDouble("balance");
boolean isActive = rs.getBoolean("active");
java.sql.Date dob = rs.getDate("date_of_birth");

System.out.println("ID: " + userId + ", Name: " + username + ", Balance: " + balance + ", Active:
" + isActive + ", DOB: " + dob);
}

By default, a ResultSet in JDBC is forward-only, meaning you can only move forward through the
rows. However, if you need to navigate backward, forward, or jump to specific rows, you can create a
scrollable ResultSet using TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE.
6. Processing the Result Set

Creating a Scrollable ResultSet


// Create a scrollable
ResultSet Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT id, name, email FROM users");

rs.last(); // Move cursor to the last


System.out.println("Total Rows: " + rs.getRow()); // Get total row count

rs.first(); // Move cursor to the first row


System.out.println("First Row -> ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));

if (rs.previous()) // Move cursor to the previous row (if available)


{ System.out.println("Previous Row -> ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); }
else
{ System.out.println("No previous row (Already at first row).");
}
6. Processing the Result Set
Key Cursor Methods for ResultSet

Method Description
rs.first() Moves the cursor to the first row.
rs.last() Moves the cursor to the last row.
rs.previous() Moves the cursor to the previous row.
rs.next() Moves the cursor to the next row.
rs.absolute(int rowNumber) Moves the cursor to a specific row.
rs.beforeFirst() Moves the cursor before the first row.
rs.afterLast() Moves the cursor after the last row.
rs.getRow() Returns the current row number.
7. Closing the Statement Object ,ResultSet and Connection

• After executing a query and processing the results, always close ResultSet and Statement
before closing the connection.
• After completing database operations, it is essential to close the database connection to
free up resources and prevent potential issues like memory leaks, connection leaks, and
performance degradation.

Why Close ResultSet and Statement? // Close resources


rs.close();
• Prevents memory leaks. stmt.close();
• Releases database resources. Conn.close
• Avoids exceeding database connection limits.
• Ensures better application performance.

From Java 7 onward, the try-with-resources statement automatically closes JDBC objects when the try
block finishes.
Example
import java.sql.*; // Close resources
rs.close();
public class JDBCDemo { stmt.close();
public static void main(String[] args) { conn.close();
String url = "jdbc:mysql://localhost:3306/mydatabase"; } catch (SQLException e) {
String user = "root"; System.out.println("Database error: " + e.getMessage());
String password = "password"; } catch (ClassNotFoundException e) {
try { System.out.println("JDBC Driver not found!");
// Load JDBC driver }
Class.forName("com.mysql.cj.jdbc.Driver"); }
// Establish database connection }
Connection conn = DriverManager.getConnection(url, user, password);
// Create Statement
Statement stmt = conn.createStatement();
// Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// Process results
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
Types of JDBC Drivers
JDBC Driver is a software component that is used to interact
with the java application with the database. The purpose
of JDBC driver is to convert java calls into database-specific
calls and database specific calls into java calls.

• Type 1
• JDBC-ODBC Bridge
• Type 2
• Native API, partially java driver
• Type 3
• JDBC Network Protocol Driver, partially java
• Type 4
• Native-protocol pure Java driver (100% Java )
https://medium.com/@prashant.srivastava
7744/java-jdbc-driver-b62fd5f6a33a
Type 1 Driver
• This driver is also known as JDBC-ODBC bridge Driver. Internally this Driver will take the support of ODBC Driver to
communicate with the database. Type-1 Driver convert JDBC calls into ODBC calls and ODBC Driver convert ODBC calls
into database-specific calls.
• Using Type-1 Driver for prototyping only and not for production purposes.
Type 2 Driver
• Native API driver converts JDBC calls into database-specific native libraries calls and these calls are directly understood by
the database engine.
• Large database vendors, such as Oracle and IBM, use the Type-2 driver for their enterprise databases.
• Type-2 Drivers aren’t architecturally compatible.
• Type-2 Drivers force developers to write platform-specific code.
Type 3 Driver/ Network Protocol Driver
• For database middle-ware, Type-3 JDBC drivers are pure Java drivers.
• Java application communicates with Network Protocol driver. Network protocol driver converts JDBC calls into middle-wear
specific calls, the middle-wear server communicates with database, middle-wear server convert middle-wear specific calls
into database-specific calls.
Type 3 Driver/ Pure Java Driver
• It is also known as the Thin driver. The thin driver converts JDBC calls into database-specific calls directly.
• Thin driver directly communicates with the database by using database specific native protocol provided by the database
vendor.
• It is a platform, independent Driver.
Which JDBC Drivers should be used?

• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is 4.
• If your Java application is accessing multiple types of databases at the same time, type 3 is
the preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
• The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
Comparison of all types of JDBC Drivers

Thick Driver:
If the database driver requires some extra
component to communicate with database
such type of driver is called the Thick driver.
Example: Type-1,Type-2,Type-3 Driver.

Thin Driver:
If the database driver does not require some
extra component to communicate with
database such type of driver is called the
Thin driver.
Example: Type-4 Driver.
MVC Framework
MVC is a design pattern used in software development to
separate an application into three interconnected
components: Model, View, and Controller. This separation
helps in organizing code, making it easier to manage, test,
and scale.

How MVC Works?

The three parts of MVC are:


1.Model: Defines the structure of the data
2.View: Handles the user interface and data presentation
3.Controller: Updates the model and view based on user input.
MVC Components
Model (M) – Data & Business Logic
• Represents data and business logic.
• Interacts with the database and performs operations like fetching, inserting, updating data.
• Example: A Student class that fetches student records from a database.

View (V) – User Interface (UI)


• Handles UI representation of the data.
• Displays information to users and takes user input.
• Example: An HTML page or a GUI form showing student details.

Controller (C) – Request Handling & Communication


• Acts as a bridge between Model and View.
• Processes user input, calls the Model for data, and updates the View accordingly.
• Example: A Java Servlet or Spring Controller handling requests and responses.
How MVC Works in Project Development?

Step 1: User requests a webpage (View).


Step 2: Controller processes the request.
Step 3: Model fetches required data.
Step 4: Controller sends data to View.
Step 5: View displays the response to the
user.
Example: Student Management System
A Student Management System where a user requests student details, and the application retrieves and displays
them using Spring Boot (Java) and JSP (View).
1. Model (M) – Student.java (Handles Data & Logic): Represents the Student entity and fetches data from the
database.
package com.example.model;

public class Student {


private int id;
private String name;
private String course;

public Student(int id, String name, String course) {


this.id = id;
this.name = name;
this.course = course;
}

// Getters and Setters


public int getId() { return id; }
public String getName() { return name; }
public String getCourse() { return course; }
}
Example: Student Management System

2. Controller (C) – StudentController.java (Handles Requests & Logic): Receives the user request
and fetches student data.

package com.example.controller;
import com.example.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class StudentController {

@GetMapping("/student")
public String getStudent(Model model) {
// Simulating fetching student details
Student student = new Student(1, "Abhay", "Computer Science");

// Adding student data to Model


model.addAttribute("student", student);

// Returning view name


return "studentView";
}
}
Example: Student Management System

3. View (V) – studentView.jsp (User Interface): Displays student details.

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8"%> How the Output is Generated?
<html>
<head> 1️⃣ User requests http://localhost:8080/student.
<title>Student Details</title> 2️⃣ StudentController.java retrieves student details
</head> (id=1, name="Abhay", course="Computer Science").
<body> 3️⃣ Model (Student.java) sends the data to View
<h2>Student Details</h2> (studentView.jsp).
<p><strong>ID:</strong> ${student.id}</p> 4️⃣ JSP renders the output by replacing ${student.id},
<p><strong>Name:</strong> ${student.name}</p> ${student.name}, and ${student.course} with actual
<p><strong>Course:</strong> ${student.course}</p> values.
</body>
</html>
Sequences
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to
produce unique values on demand. A sequence is a user defined schema bound object that generates a
sequence of numeric values.

Characteristics of Sequences:
• User-Defined Object: A sequence is explicitly created and managed by users.
• Schema-Bound: It exists within a specific database schema.
• Automatic Generation: Produces unique values sequentially (ascending or descending).
• Configurable: Users can define:
• Start value (initial number)
• Increment step (interval between values)
• Min/Max value (optional limits)
• Cycle option (whether to restart after reaching max/min value)
• Independent of Tables: Unlike AUTO_INCREMENT, sequences are separate objects and can be used across
multiple tables.
Sequences Contd.
Syntax
CREATE SEQUENCE sequence_name START WITH initial_value INCREMENT BY increment_value MINVALUE
minimum value MAXVALUE maximum value CYCLE|NOCYCLE ;

Example
CREATE SEQUENCE order_seq START WITH 1000 INCREMENT BY 5 MINVALUE 1000 MAXVALUE
1020 CYCLE;

• START WITH 1000 → First generated value is 1000.


• INCREMENT BY 5 → Each next value increases by 5.
• MINVALUE 1000, MAXVALUE 1020 → The sequence will range from 1000 to 1020.
• CYCLE → When it reaches 1020, it restarts from 1000.
Sequences Contd.
Output (First 5 Calls)
Fetching Next Values Call Number Output (NEXTVAL)
1st Call 1000
SELECT order_seq.NEXTVAL;
2nd Call 1005
3rd Call 1010
4th Call 1015
5th Call 1020
Sequence Cycling (After Reaching MaxValue)
After reaching 1020, since we used CYCLE, the sequence restarts at 1000.

Call Number Output (NEXTVAL)


6th Call 1000
7th Call 1005
Sequences Contd.
Using the Sequence in an Insert Query

INSERT INTO orders (order_id, customer_name) VALUES (order_seq.NEXTVAL, 'Abhay');

order_id customer_name
1000 Abhay
Dual Tables
• DUAL is a special one-row, one-column table present in Oracle databases by default.
• It is owned by SYS (which manages the data dictionary).
• It has a single column named DUMMY, which is of type VARCHAR2(1) and contains the value
'X'.
• Every user can access the DUAL table.

Why is DUAL Used?


DUAL is useful for executing queries that do not require actual tables, such as:
- Performing calculations
- Using functions (e.g., SYSDATE, USER)
- Fetching sequence values
Uses of DUAL Tables
Mathematical Calculation
SELECT 10 * 5 FROM DUAL; 10 * 5
50
Using System Functions

SELECT SYSDATE FROM DUAL; -- Returns current date SYSDATE


08-MAR-25
Fetching a Sequence Value
SELECT order_seq.NEXTVAL FROM DUAL;
NEXTVAL
Why Can’t We DELETE or TRUNCATE the Default DUAL? 1000

DELETE from DUAL (Not Allowed) – Oracle does not allow deleting from the default DUAL table,
but you can delete from a user-created DUAL table.
TRUNCATE DUAL (Not Allowed) – Since the default DUAL table is a system table, TRUNCATE is
not permitted, but it works on a custom DUAL table.
Data Type Management

• The Microsoft JDBC Driver for SQL Server uses the JDBC basic data types to convert the SQL Server
data types to a format that can be understood by the Java programming language, and vice versa.
• The JDBC driver provides support for the JDBC 4.0 API, which includes the SQLXML data type, and
National (Unicode) data types, such as NCHAR, NVARCHAR, LONGNVARCHAR, and NCLOB.

How Java data types map to SQL Server types using JDBC.

Java: String name = "Abhay";


JDBC Converts: String → VARCHAR
SQL Server Stores: 'Abhay' in VARCHAR(50)
Data Type Mapping
A structured table showing the default mappings between SQL Server, JDBC, and Java programming
language data types:

SQL Server Data Type JDBC Data Type Java Data Type
INT INTEGER int
BIGINT BIGINT long
SMALLINT SMALLINT short
TINYINT TINYINT byte
BIT BIT boolean
DECIMAL / NUMERIC DECIMAL BigDecimal
FLOAT DOUBLE double
REAL REAL float
CHAR(n) CHAR String
VARCHAR(n) VARCHAR String
TEXT LONGVARCHAR String
NCHAR(n) NCHAR String
Data Type Mapping Contd.
SQL Server Data Type JDBC Data Type Java Data Type
NVARCHAR(n) NVARCHAR String
NTEXT LONGNVARCHAR String
BINARY(n) BINARY byte[]
VARBINARY(n) VARBINARY byte[]
IMAGE LONGVARBINARY byte[]
DATE DATE java.sql.Date
TIME TIME java.sql.Time
DATETIME / SMALLDATETIME TIMESTAMP java.sql.Timestamp
DATETIME2 TIMESTAMP java.sql.Timestamp
DATETIMEOFFSET TIMESTAMP_WITH_TIMEZONE java.time.OffsetDateTime
SQLXML SQLXML java.sql.SQLXML
Data Type Mapping Contd.
Handling Date & Time in SQL Server with Java JDBC

Using java.sql.Time with SQL Server


Issue: By default, SQL Server treats java.sql.Time as datetime.
Solution: Set sendTimeAsDatetime=false in the connection properties.

Working with datetimeoffset in SQL Server


SQL Server datetimeoffset stores date, time, and timezone offset.

Working with java.sql.Timestamp Issue in SQL Server 2016+


Issue : SQL Server converts datetime to datetime2 differently, causing mismatches with
java.sql.Timestamp.
Solution:
- Use datetime2(3) instead of datetime.
- Convert Timestamp to String before comparison.
- Change database compatibility level to 120 or below.
Questions
• What is JDBC, and why is it used in Java?
• Explain the four types of JDBC drivers and their differences.
• How do you establish a database connection in Java using JDBC?
• What is Connection Pooling in JDBC, and why is it important?
• What is the difference between Statement, PreparedStatement, and CallableStatement?
• How do you perform CRUD operations (Create, Read, Update, Delete) using JDBC?
• Write a Java program to execute a SELECT query using JDBC.
• What is a ResultSet, and what are its different types?
• What is a SEQUENCE in SQL, and why is it used?
• How do you create and use a SEQUENCE in Oracle?
• What is the DUAL table in Oracle, and what is its purpose?
• Why can’t we DELETE or TRUNCATE the default DUAL table?
• What is the default mapping between SQL data types and Java data types in JDBC?
• Why can’t java.sql.Timestamp be used for comparing datetime values in SQL Server 2016 and later?
• What is MVC (Model-View-Controller) in Java?
• How is MVC implemented in a Java web application?
• Explain the roles of Model, View, and Controller in an MVC-based project.

You might also like