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

Structure of JDBC Driver: JDBC Drivers JDBC Apis 4 Types of JDBC Drivers

Java Database Connectivity (JDBC) is an API that allows Java applications to connect and interact with relational databases. It includes various components such as JDBC drivers, DriverManager, and ResultSet, with four types of JDBC drivers available for different use cases. The document also outlines the architecture, key features, and provides a simple example of connecting to a MySQL database using JDBC.

Uploaded by

pathaksapna34
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 views39 pages

Structure of JDBC Driver: JDBC Drivers JDBC Apis 4 Types of JDBC Drivers

Java Database Connectivity (JDBC) is an API that allows Java applications to connect and interact with relational databases. It includes various components such as JDBC drivers, DriverManager, and ResultSet, with four types of JDBC drivers available for different use cases. The document also outlines the architecture, key features, and provides a simple example of connecting to a MySQL database using JDBC.

Uploaded by

pathaksapna34
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/ 39

Java Database Connectivity (JDBC) is an application programming interface (API) for the Java programming language that defines

how a client can access and interact with any kind of tabular data, especially a relational database. JDBC Drivers uses JDBC
APIs which was developed by Sun Microsystem, but now this is a part of Oracle. There are 4 types of JDBC drivers. It is part
of the Java Standard Edition platform, from Oracle Corporation. It acts as a middle-layer interface between Java applications
and databases.
The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query
Structure of JDBC Driver
The above JDBC Driver structure illustrates the architecture of JDBC driver, where an application interacts with the JDBC API.
The API communicates with the JDBC Driver Manager, which manages different database drivers e.g. SQL server, Oracle to
establish database connectivity.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine rather than the server) that translate requests from Java
programs into a protocol understood by the DBMS. These drivers are software components that implement the interfaces in
the JDBC API, allowing Java applications to interact with a database. Sun Microsystems (now Oracle) defines four types of
JDBC drivers, which are outlined below:
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 – Type 1 Driver
Type-1 driver or 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. Type-1 driver is also called Universal driver because it can be used
to connect to any of the databases.

Advantages
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.
Disadvantages
 As a common driver is used in order to interact with different databases, the data transferred through this driver is not so
secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API Driver – Type 2 Driver ( Partially Java Driver)
The Native API driver uses the client -side libraries of the database. This driver converts JDBC method calls into native calls of
the database API. In order to interact with different database, this driver needs their local API, that’s why data transfer is much
more secure as compared to type-1 driver. This driver is not fully written in Java that is why it is also called Partially Java
driver.

Advantage
 Native-API driver gives better performance than JDBC-ODBC bridge driver.
 More secure compared to the type-1 driver.
Disadvantages
 Driver needs to be installed separately in individual client machines
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
 It is a database dependent driver.
3. Network Protocol Driver – Type 3 Driver (Fully Java Driver)
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. Here all the database connectivity drivers are present in a single server, hence no need of
individual client-side installation.

Advantages
 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can perform many tasks like auditing, load balancing,
logging etc.
 Switch facility to switch over from one database to another database.
Disadvantages
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the
middle tier.
4. Thin Driver – Type 4 Driver (Fully Java Driver)
Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
Advantages
 Does not require any native library and Middleware server, so no client-side or server-side installation.
 It is fully written in Java language, hence they are portable drivers.
Disadvantage
 If the database changes, a new driver may be needed.
Which Driver to use When?
 If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is type-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.
JDBC (Java Database Connectivity)

JDBC (Java Database Connectivity) is an API in Java that enables applications to interact with databases. It allows a Java
program to connect to a database, execute queries, and retrieve and manipulate data. By providing a standard interface,
JDBC ensures that Java applications can work with different relational databases like MySQL, Oracle, PostgreSQL, and more.
JDBC Architecture
Explanation:
 Application: It is a Java applet or a servlet that communicates with a data source.
 The JDBC API: It allows Java programs to execute SQL queries and retrieve results. Key interfaces include Driver,
ResultSet, RowSet, PreparedStatement, and Connection. Important classes include DriverManager, Types, Blob, and Clob.
 DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to effectively
connect enterprise applications to databases.
 JDBC drivers: These drivers handle interactions between the application and the database.
The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as described
below:
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. Queries are sent to the database, and
results are returned directly to the application. In a client/server setup, the user’s machine (client) communicates with a remote
database server.
Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services, which interacts with the database. The database results are processed
by the middle tier and then sent back to the user.
Structure:
Client Application -> Application Server -> JDBC Driver -> Database
JDBC Components
There are generally 4 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 includes two key packages
 java.sql: This package, is the part of Java Standard Edition (Java SE) , which contains the core interfaces and classes for
accessing and processing data in relational databases. It also provides essential functionalities like establishing
connections, executing queries, and handling result sets
 javax.sql: This package is the part of Java Enterprise Edition (Java EE) , which extends the capabilities of java.sql by
offering additional features like connection pooling, statement pooling, and data source management.
It also provides a standard to connect a database to a client application.
2. JDBC Driver Manager
Driver manager is responsible for loading the correct database-specific driver to establish a connection with the database. It
manages the available drivers and ensures the right one is used to process user requests and interact with the database.
3. JDBC Test Suite
It is used to test the operation(such as insertion, deletion, updating) being performed by JDBC Drivers.
4. 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 (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver) – It is deprecated and no longer supported since Java 8. Instead modern
drivers like the Type – 4 driver are widely used.
JDBC Classes and Interfaces
Class/Interfaces Description

DriverManager Manages JDBC drivers and establishes database connections.

Connection Represents a session with a specific database.

Statement Used to execute static SQL queries.

PreparedStatement Precompiled SQL statement, used for dynamic queries with parameters.

CallableStatement Used to execute stored procedures in the database.

ResultSet Represents the result set of a query, allowing navigation through the rows.

SQLException Handles SQL-related exceptions during database operations.

Steps to Connect to MySQL Database Using JDBC


Step 1: Load the JDBC Driver
Class.forName(“com.mysql.cj.jdbc.Driver”);
Step 2: Establish a Connection
Connection connection = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/your_database”,
“your_username”,
“your_password”
);
Step 3: Create a Statement
Statement statement = connection.createStatement();
Step 4: Execute a Query
String query = “INSERT INTO students (id, name) VALUES (101, ‘John Doe’)”;
int rowsAffected = statement.executeUpdate(query);
System.out.println(“Rows affected: ” + rowsAffected);
Step 5: Close the Connection
statement.close();
connection.close();
Create a Simple JDBC Application
The below Java program demonstrates how to establish a MYSQL database connection using JDBC and execute a query.
// Java program to implement a simple JDBC application
import java.sql.*;

public class Geeks {


public static void main(String[] args)
{
// Database URL, username, and password

// Replace with your database name


String url
= "jdbc:mysql://localhost:3306/your_database";

// Replace with your MySQL username


String username = "your_username";

// Replace with your MySQL password


String password = "your_password";

// Updated query syntax for modern databases


String query
= "INSERT INTO students (id, name) VALUES (109, 'bhatt')";

// Establish JDBC Connection


try {

// Load Type-4 Driver


// MySQL Type-4 driver class
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
Connection c = DriverManager.getConnection(
url, username, password);

// Create a statement
Statement st = c.createStatement();

// Execute the query


int count = st.executeUpdate(query);
System.out.println(
"Number of rows affected by this query: "
+ count);

// Close the connection


st.close();
c.close();
System.out.println("Connection closed.");
}
catch (ClassNotFoundException e) {
System.err.println("JDBC Driver not found: "
+ e.getMessage());
}
catch (SQLException e) {
System.err.println("SQL Error: "
+ e.getMessage());
}
}
}
Output:

Note: When the program runs successfully, a new record is added to the students table as shown below:
Key Features
 Platform Independence: It enables database operations across different platforms.
 Standard API: It provides a uniform interface for various databases.
 Support for Multiple Databases: It works with popular databases like MySQL, PostgreSQL, Oracle, etc.
 Extensibility: It offers features like batch processing, connection pooling, and transaction management.

The Driver Manager:

In Java, the DriverManager class, part of the JDBC API, manages the set of available JDBC drivers and facilitates establishing
database connections by interacting with the appropriate driver for a given database URL.
Here's a more detailed explanation:
 Purpose: The DriverManager acts as an interface between your Java application and the various JDBC drivers, allowing your
application to connect to different databases without needing to know the specifics of each driver.
 Functionality:
o Driver Management: It maintains a list of registered JDBC drivers.
o Connection Handling: When a connection is requested, the DriverManager iterates through the registered drivers and asks them
to attempt to connect to the target database URL, until a successful connection is established.
o Driver Registration: You can register JDBC drivers using DriverManager.registerDriver(Driver driver).

o Connection Retrieval: You can obtain a database connection using DriverManager.getConnection(String url, String user, String
password).
 Example:
import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "myuser";
String password = "mypassword";

try {
// Load the JDBC driver (example for MySQL)
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish a connection
Connection connection = DriverManager.getConnection(url, user, password);
if (connection != null) {
System.out.println("Connected to the database!");
// Perform database operations here
connection.close(); // Close the connection
} else {
System.out.println("Failed to connect to the database!");
}
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
}
}
}

JDBC Result Set


Java Database Connectivity is Java-based technology and that provides a standard API for accessing databases in Java applications. The Key
Component of Java Database Connectivity is the ResultSet. JDBC driver allows developers to read and manipulate data from the database.
The JDBC ResultSet is Object which represents the result of a SQL Query executed on a database. It acts as a cursor to navigate through the
retrieved data, manipulate data, Fetching Specific columns and others. In this article, we will learn more about JDBC Result Set.
JDBC Result Set in Java
The ResultSet is essentially a table of data where each row represents a record and each column represents a field in the database. The
ResultSet has a cursor that points to the current row in the ResultSet and we can able to navigate in ResultSet by using the next(), previous(),
first(), and last() methods. We can retrieve data by using different methods like getString(), getInt(), getDouble() and other methods.
In Java, the ResultSet is the Object which is used for holding the result of a database query typically the SQL select statement. And It is the
part of JDBC API which is used for interacting with relational databases. The ResultSet allows us over the rows of tables returned by the SQL
query and extract a specific column from the SQL query result.
Syntax:
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table");

while (rs.next()) {
// Process the result set
}

rs.close();
stmt.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace(); // Handle the exception
}
Common Operations with ResultSet:
 Fetching data from database: We can fetch data from the database based on the requirements by using conditional statements.
 Navigating the ResultSet: We can able navigating the ResultSet by using methods like next(), previous(), first(), and last().
 Getting column values: We can fetch column values with specific conditions or without conditions.
 Closing the result: Once database operations are completed we need close the connections related to database here we close the ResultSet
connection. By using close method.

Types of ResultSet
There are three different characteristics by which ResultSet types are differentiated
1. Scrollability: Determines whether you can move back and forth in the ResultSet
 TYPE_FORWARD_ONLY: Can only move forward through the rows
 TYPE_SCROLL_INSENSITIVE: Can move forward and backward but changes are not reflect ResultSet
 TYPE_SCROLL_SENSITIVE: Can move forward and backward but changes are affect the ResultSet
2. Concurrency: Determines whether you can update the ResultSet
 CONCUR_READ_ONLY: Can only read data
 CONCUR_UPDATABLE: Allows updates to the ResultSet
3. Holdability: Determines what happens to the ResultSet when a Transaction is committed.
 HOLD_CURSORS_OVER_COMMIT: The ResultSet remains open after a commit
 CLOSE_CURSORS_AT_COMMIT: The ResultSet closes after a commit
Category of Methods in Result Set
We have different types of Methods are available based on their functionality below we listed them for you reference.
i). Navigating a ResultSet:
Basically these methods are allow is to navigating through the ResultSet and we can navigate in different ways, Below We provide those
methods to navigate in the ResultSet.
Method Description

next() used for move next row in the ResultSet.

previous() used for move to previous row in the ResultSet

first() used for move to first row in the ResultSet

last() used for move to last row in the ResultSet

absolute(int row) used to move to specific row

relative(int rows) used for Moves forward or backward by the specified number of rows

beforeFirst() used for Positions the cursor before the first row

afterLast() used for Positions the cursor after the last row

ii). Retrieving Data from a ResultSet:


These methods retrieve data from the current row in the ResultSet. And also You can retrieve data by column index or column name.
Method Description

getInt(int columnIndex) used for Retrieves an integer from the specified column

getString(int columnIndex) used for Retrieves a string from the specified column
Method Description

getDouble(int columnIndex) used for Retrieves a double from the specified column

getBoolean(int columnIndex) used for Retrieves true or false from the specified column

getDate(int columnIndex) used for Retrieves a java.sql.Date

getObject(int columnIndex) used for Retrieves any type of object

getArray(int columnIndex) used for Retrieves a SQL array

iii). Updating Data in a ResultSet:


These methods allow you to update data in the Result.
Method Description

updateInt(int columnIndex, int x) used for Updates an integer value in the specified column

updateString(int columnIndex, String x) used for Updates a string value

updateBoolean(int columnIndex, boolean x) used for Updates a boolean value

updateRow() used for Updates a row

deleteRow() used for delete a row

Employees Table Structure:


We create a employees table in work database. Below we provide table structure
Program Implementing the JDBC Result Set
In this example we perform CRUD operations by using ResultSet. After running this program as java application It show four options to you.
Need to select 1 to 4 based on your requirement below I provide the example with related images.
package geeksforgeeks;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class JDBCOperations {

// Establish database connection


private static Connection getConnection()
throws Exception {

String jdbcUrl = "jdbc:mysql://localhost:3306/data";


String jdbcUser = "root";
String jdbcPassword = "password";
return DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
}

// Insert record into the database


private static void insertRecord(Connection connection,
String name, double salary)
throws Exception {
String query = "INSERT INTO employees (name, salary) VALUES (?, ?)";

PreparedStatement preparedStatement
= connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setDouble(2, salary);
preparedStatement.executeUpdate();

System.out.println("Record inserted successfully.");


}

// Update record in the database


private static void updateRecord(Connection connection,
int id, String name,double salary)
throws Exception {

String query
= "UPDATE employees SET name = ?, salary = ? WHERE id = ?";

PreparedStatement preparedStatement
= connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setDouble(2, salary);
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();

System.out.println("Record updated successfully.");


}

// Retrieve records from the database


private static void
retrieveRecords(Connection connection) throws Exception {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");

System.out.println("Records in the database:");


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double salary = resultSet.getDouble("salary");
System.out.println("ID: " + id + ", Name: " + name +
", Salary: " + salary);

}
}

// Delete record from the database


private static void deleteRecord(Connection connection,
int id)
throws Exception {
String query = "DELETE FROM employees WHERE id = ?";
PreparedStatement preparedStatement
= connection.prepareStatement(query);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
System.out.println("Record deleted successfully.");
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
try {
Connection connection = getConnection();

System.out.println("Select an operation:");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Retrieve");
System.out.println("4. Delete");

int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("Enter name:");
String nameToInsert = scanner.next();
System.out.println("Enter salary:");
double salaryToInsert = scanner.nextDouble();
insertRecord(connection, nameToInsert,
salaryToInsert);
break;

case 2:
System.out.println("Enter ID to update:");
int idToUpdate = scanner.nextInt();
System.out.println("Enter new name:");
String nameToUpdate = scanner.next();
System.out.println("Enter new salary:");
double salaryToUpdate
= scanner.nextDouble();
updateRecord(connection, idToUpdate,
nameToUpdate, salaryToUpdate);
break;

case 3:
retrieveRecords(connection);
break;

case 4:
System.out.println("Enter ID to delete:");
int idToDelete = scanner.nextInt();
deleteRecord(connection, idToDelete);
break;

default:
System.out.println("Invalid choice.");
break;
}

// Close the connection at the end


connection.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
}

Explanation of the above Program:


 Database Connection: Create Database connection by using configuration details like username, password, database name and other
information. Below we provide the database connection java code.
 Insert Record: Now we implement logic for inserting new records by using this connection object. And we use PreparedStatement for
preventing SQL Injection and It will takes input data in the form placeholders. After that we execute the SQL query by using
executeUpdate method from PreparedStatement.
 Update Record: Now we implement logic for update function. We employees details based on their existing employee id only. It is same
like inserting new record but before that we fetch existing data then only we can able to update the data.
 Fetch All Records: Now we develop logic for fetching all records from the table by using ResultSet object. First we execute the SQL
query then hold that result in ResultSet Object. Then we iterate that data and print line by line the entire data in the table.
 Delete Record by Using ID: In this function we can delete an existing employee record by using employee ID from the Table.
 Main Function: In main function of the class, We develop logic for selecting operation from the console by using switch statement in
java. Based on the selection you can perform related database operation. Below we provide that entire code for your reference.
Output:
Showing available database operations

Now enter option 1, That means you can ready to insert data into database.
Now enter option 2, That means you can ready to update employee data by employee ID

Now enter option 3, That means you can fetch all data from table.
Now enter option 4, That means you can delete an employee details by using employee ID.

JDBC API
JDBC API is mainly divided into two package. Each when we are using JDBC, we have to import these packages to
use classes and interfaces in our application.
1. java.sql

2. javax.sql

java.sql package

This package include classes and interface to perform almost all JDBC operation such as creating and executing SQL
Queries.

Important classes and interface of java.sql package

classes/interface Description

java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.

java.sql.Connection creates a connection with specific database

java.sql.CallableStatement Execute stored procedures

java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.


java.sql.Date Provide support for Date SQL type.

java.sql.Driver create an instance of a driver with the DriverManager.

java.sql.DriverManager This class manages database drivers.

java.sql.PreparedStatement Used to create and execute parameterized query.

It is an interface that provide methods to access the result


java.sql.ResultSet
row-by-row.

java.sql.Savepoint Specify savepoint in transaction.

java.sql.SQLException Encapsulate all JDBC related exception.

java.sql.Statement This interface is used to execute SQL statements.


DatabaseMetaData Comprehensive information about the database as a whole.

An interface that must be implemented when a Driver wants


DriverAction
to be notified by DriverManager.

An object that can be used to get information about the


ResultSetMetaData
types and properties of the columns in a ResultSet object.

The representation (mapping) in the Java programming


RowId
language of an SQL ROWID value.

The representation of a savepoint, which is a point within the


Savepoint current transaction that can be referenced from
the Connection.rollback method.

The interface used for the custom mapping of an SQL user-


SQLData defined type (UDT) to a class in the Java programming
language.
An input stream that contains a stream of values representing
SQLInput
an instance of an SQL structured type or an SQL distinct type.

The output stream for writing the attributes of a user-defined


SQLOutput
type back to the database.

An object that is used to identify a generic SQL type, called a


SQLType
JDBC type or a vendor specific data type.

cThe mapping in the JavaTM programming language for the


SQLXML
SQL XML type.

The object used for executing a static SQL statement and


Statement
returning the results it produces.

The standard mapping in the Java programming language for


Struct
an SQL structured type.
Interface for JDBC classes which provide the ability to retrieve
Wrapper the delegate instance when the instance in question is in fact
a proxy class.

The javax.sql package

This package is also known as JDBC extension API. It provides classes and interface to access server-side data.

Important classes and interface of javax.sql package

classes/interface Description

javax.sql.ConnectionEvent Provide information about occurence of event.

Used to register event generated


javax.sql.ConnectionEventListener
by PooledConnection object.

Represent the DataSource interface used in an


javax.sql.DataSource
application.
javax.sql.PooledConnection provide object to manage connection pools.

Interface that defines the methods which are


CommonDataSource common between DataSource, XADataSource and
ConnectionPoolDataSource.

The interface that adds support to the JDBC API for


RowSet
the JavaBeans™ component model.

The interface that a RowSet object implements in


RowSetInternal order to present itself to a RowSetReader or
RowSetWriter object.

An interface that must be implemented by a


component that wants to be notified when a
RowSetListener
significant event happens in the life of
a RowSet object.
An object that contains information about the
RowSetMetaData
columns in a RowSet object.

The facility that a disconnected RowSet object calls


RowSetReader
on to populate itself with rows of data.

An object that implements


RowSetWriter
the RowSetWriter interface, called a writer.

An object that registers to be notified of events that


StatementEventListener occur on PreparedStatements that are in the
Statement pool.

An object that provides support for distributed


XAConnection
transactions.

A factory for XAConnection objects that is used


XADataSource
internally.
JDBC Exception Classes

Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases.
While establishing connections and executing queries, we developers often encounter SQLExceptions, which are
inevitable in the real world. Handling those exceptions is crucial in the development of applications. Now let's
understand more about SQL Exception.
Understanding SQL Exception
Exception is a type of condition when a program encounters a problem in execution and quits with a problematic error
message. In JDBC, when the program has trouble with a data source, it throws SQLException.
Note: An SQLException can occur in the JDBC Driver or inside the database.
SQL Exception methods in Java:
METHOD NAME DESCRIPTION

Gets the error number associated with the


getErrorCode()
exception.

This method gets the JDBC driver’s error


getMessage()
message for

Gets the XOPEN SQLstate string. This method


getSQLState()
can return null.

In the exception chain, gets the next Exception


getNextException()
object

Prints the current exception, or throwable, and


printStackTrace()
it’s backtrace to a standard error stream.

To the print the stream we have specified, prints


printStackTrace(PrintStream s)
this throwable and its backtrace.
METHOD NAME DESCRIPTION

Prints this throwable and it’s backtrace to the


printStackTrace(PrintStream s)
print writer you specify.

The below-described code describes how to handle SQL Exception.


 Initial part of the code is to connect to the sql server i.e. username and password are declared.

 The resultantSet is initialized and declared.

 Once the server gets connected then the query gets executed.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SQLExceptionExample {


public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// establish a connection to the database


connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username", "password");

// Your SQL query with an intentional error (table name is misspelled)


String sql = "SELECT * FROM non_existent_table";

// create a PreparedStatement
preparedStatement = connection.prepareStatement(sql);
// execute the query (this will throw an SQLException in case of an error)
preparedStatement.executeQuery();
} catch (SQLException | ClassNotFoundException e) {
// handle the SQL exception
handleSQLException(e);
} finally {
// close the resources in the finally block
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
handleSQLException(e);
}
}
}

private static void handleSQLException(SQLException e) {


// handle the SQL exception
int errorCode = e.getErrorCode();
String sqlState = e.getSQLState();
String errorMessage = e.getMessage();

System.out.println("SQL Error Code: " + errorCode);


System.out.println("SQL State: " + sqlState);
System.out.println("Error Message: " + errorMessage);

e.printStackTrace();
}
}
Note: To load the JDBC Driver, first connect to the database (SQL) and fetch that link to establish the connection.

Output:
The Output of the above code will intentionally create SQL Exception error since there is no non-existence table in the database. This co

de lets you to understand the SQL Exception Methods. Source Code:


Below is the entire source code which follows the connection steps.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SQLException_Example {


// Define JDBC Driver
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

// Database URL, username, and password


static final String dburl = "jdbc:mysql://localhost/STOREDB";
static final String dbuser = "root";
static final String dbpass = "root";

public static void main(String[] args) throws SQLException {


Connection con = null;
Statement stmt = null;

try {
// Connecting to the server and database
con = DriverManager.getConnection(dburl, dbuser, dbpass);

// Initialize Statement
stmt = con.createStatement();

// SQL Query
String query = "SELECT * FROM ITEM";

// Execute Query And Get ResultSet


ResultSet rset = stmt.executeQuery(query);
while (rset.next()) {
System.out.print("ID: " + rset.getInt(1));
System.out.print(" Product: " + rset.getString(2));
System.out.println(" Price: " + rset.getString(3));
}
} catch (SQLException e) {
// Catch SQLException, print error and stack trace
System.err.println("Cannot connect! ");
e.printStackTrace();
} finally {
// Finally block to ensure closing connection
System.out.println("Closing the connection.");
if (con != null) try { con.close(); } catch (SQLException ignore) {}
}
}
}
 The above program establishes a connection to the MySQL database (STOREDB) using the provided URL, username, and password.
 To load the JDBC Driver, first connect to the database (SQL) and fetch that link to establish the connection.
 A Statement object is created to execute SQL queries.
 The SELECT query is executed, and the results are stored in a ResultSet.
 The program iterates through the result set and prints the values of the ID, Product, and Price columns.
 If a SQLException occurs during the execution of the program, it is caught, and its details are printed.
 The details that are printed is included in the output of methods of SQL Exception.
 The finally block ensures that the connection is closed, whether an exception occurs or not.
Output:
Java Database Connectivity with 5 Steps
1. 5 Steps to connect to the database in java
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:

 Register the Driver class


 Create connection
 Create statement
 Execute queries
 Close connection

You might also like