Chapter 6
Chapter 6
(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
The JDBC API is part of the java.sql package and provides various interfaces, classes, and
exceptions to facilitate database connectivity in Java applications.
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.
Once the JDBC driver is loaded, the next step is to establish a connection between the Java application and
the database using DriverManager.getConnection().
try {
// Establish connection
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Database connected successfully!");
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.
We create a Statement object from a Connection using the createStatement() method. Always
close the Statement object after execution to free resources.
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.
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
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.
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.
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");
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;
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.
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.
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