JDBC
JDBC
WITH DATABASE:JDBC
Getting started with JDBC, Introduction to JDBC, Components of JDBC, JDBC Architecture, Types of
Drivers, Working with JDBC APIs, Creating a Simple Application, Working with Prepared Statement,
ResultSet, Transaction Management.
TOPICS
• Introduction to JDBC
• JDBC Architecture
• Components of JDBC
• Types of JDBC Drivers
• JDBC API
• Step-by-Step procedure to Establish a connection
• 68,69,73,76,81,82,94,95,98,a0,a2,,a6,a8,b0,b3,b6,b7,c2,c5,c6,c7,c8,c
9,d2,le-11,
JDBC
• JDBC (Java Database Database Connectivity) is a Sun Microsystems
specification.
• It is the Java API that is responsible for connecting to a database,
issuing queries and commands, and processing database result sets.
• To access spreadsheets and databases, JDBC and database drivers
operate together.
• The components of JDBC that are utilized to connect to the database
are defined by the design of JDBC. The JDBC API classes and interfaces
enable an application to send a request to a specific database.
Purpose of JDBC
Java programming language is used to develop enterprise applications. These
applications are developed with intention of solving real-life problems and need to
interact with databases to store required data and perform operations on it. Hence, to
interact with databases there is a need for efficient database connectivity, ODBC(Open
Database Connectivity) driver is used for the same.
ODBC is an API introduced by Microsoft and used to interact with databases. It can be
used by only the windows platform and can be used for any language like C, C++, Java,
etc. ODBC is procedural.
JDBC is an API with classes and interfaces used to interact with databases. It is used
only for Java languages and can be used for any platform. JDBC is highly recommended
for Java applications as there are no performance or platform dependency problems.
Applications of JDBC
• Connecting to data sources: JDBC allows applications to connect to data sources like
relational databases and flat files.
• Executing queries: JDBC allows applications to execute SQL queries to retrieve, update,
or delete data in a database.
• Handling data: JDBC allows applications to handle data retrieved from databases in a
structured manner.
• Managing resources: JDBC provides mechanisms to efficiently manage database
resources, such as connections and statements.
• Batch updates: JDBC allows applications to perform batch updates, which can improve
performance.
JDBC serves as a crucial bridge between Java applications and relational databases across a variety of fields
and application types.
JDBC Features:
• Platform Independence – Database operations on any OS.
• Standard API – Uniform database interaction.
• Support for Multiple Databases – Works with major relational databases.
• Dynamic SQL Execution – Construct SQL at runtime.
• PreparedStatement Support – Secure, parameterized queries.
• Batch Processing – Execute multiple statements in a single batch.
• Transaction Management – Commit and rollback support.
• ResultSet for Data Retrieval – Fetch and process query results.
• CallableStatement for Stored Procedures – Support for stored procedures.
• Metadata Retrieval – Retrieve database and result set metadata.
• Scrollable and Updatable ResultSets – Navigate and update result sets.
• Connection Pooling – Efficient database connection reuse.
• Support for Row Sets – Work with offline data sets.
• SQL Exceptions – Detailed error handling.
• Data Types Mapping – Seamless data type conversion.
• Extensibility – Integration with ORMs like Hibernate or JPA.
These features make JDBC a versatile and essential API for Java applications that need to interact with relational
databases.
JDBC Architecture
JDBC Architecture
components of JDBC
architecture are:
1. Application
2. The JDBC API
3. DriverManager
4. JDBC Drivers
5. Data Sources
1. Application: Applications in JDBC architecture are java applications like applets or servlet that
communicates with databases.
2. JDBC API: The JDBC API is an Application Programming Interface used to create Databases. JDBC
API uses classes and interfaces to connect with databases. Some of the important classes and
interfaces defined in JDBC architecture in java are the DriverManager class, Connection Interface,
etc.
4. JDBC Drivers: JDBC drivers are used to connecting with data sources. All databases like Oracle,
MSSQL, MYSQL, etc. have their drivers, to connect with these databases we need to load their
specific drivers. Class is a java class used to load drivers. Class.forName() method is used to load
drivers in JDBC architecture.
5. Data Sources: Data Sources in the JDBC architecture are the databases that we can connect using
this API. These are the sources where data is stored and used by Java applications. JDBC API helps to
connect various databases like Oracle, MYSQL, MSSQL, PostgreSQL, etc.
Types of JDBC Architecture:
The JDBC Architecture can be of two types based on the processing
models it uses. These models are
1. Two-Tier Architecture
2. Three-Tier architecture
1. Two-Tier Architecture
• 2-tier JDBC architecture model is a basic model.
• In this model, a java application communicates directly to the data sources. JDBC
driver is used to establish a connection between the application and the data
source.
• When an application needs to interact with a database, a query is directly
executed on the data source and the output of the queries is sent back to the user
in form of results.
• In this model, the data source can be located on a different machine connected to
the same network the user is connected to.
• This model is also known as a client/server configuration. Here user's machine
acts as a client and the machine on which the database is located acts as a server.
2. Three-Tier Architecture
• 3-tier model is a complex and more secure model of JDBC architecture in
java.
• In this model the user queries are sent to the middle tier and then they
are executed on the data source.
• Here, the java application is considered as one tier connected to the data
source(3rd tier) using middle-tier services.
• In this model user queries are sent to the data source using middle-tier
services, from where the commands are again sent to databases for
execution.
• The results obtained on the database are again sent to the middle-tier
and then to the user/application.
Advantages of JDBC Architecture
• It can read any database. The only condition for it to do so is that all of the drivers be properly installed.
• It pulls information from a database and converts it to XML.
• It does not necessitate the conversion of the content.
• Software maintenance is centralized with no client settings necessary. Because the driver is built in Java,
the JDBC URL or a DataSource object has all of the information required to establish a connection.
• It supports queries and stored procedures completely.
• The JDBC API contains a DataSource object that can be used to identify and connect to a data source.
This improves the code’s portability and maintainability.
• Both synchronous and asynchronous processing is supported.
• The Java API and the JDBC API work together to make application development simple and cost-
effective.
• Modules are supported.
• Even if data is housed on various database management systems, businesses can continue to use their
installed databases and access information.
Components of JDBC
Components of JDBC
JDBC has four main components that are used to connect with a
database as follows:
1. JDBC API
2. JDBC Driver Manager
3. JDBC Test Suite
4. JDBC-ODBC Bridge Drivers
1. JDBC API
JDBC API is a collection of various classes, methods, and interfaces for easy
communication with a database. JDBC API provides two different packages to
connect with different databases.
java.sql.*;
javax.sql.*;
JDBC-ODBC Bridge Drivers are used to bridge the same gap between JDBC and
ODBC drivers. The bridge translates the object-oriented JDBC method call to the
procedural ODBC function call. It makes use of the sun.jdbc.odbc package. This
package includes a native library to access ODBC characteristics.
JDBC Drivers
JDBC
Java Database Connectivity (JDBC) is an application programming interface (API) for the programming
language Java, which defines how a client may access 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:
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.
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
• 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
Disadvantage
If the database varies, then the driver will carry because it is database
dependent.
Which Driver to use When?
try
{
// Load driver class
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
// Obtain a connection
con = DriverManager.getConnection("","","");
System.out.println("Database Connected Successfully!");
//Create Query
String sql = "INSERT INTO Student(sname, scity) values('ABC','Pune')";
// Obtain a statement
st = con.createStatement();
Real-world example:
• Real-world example:
• Consider two places A and B. Now people residing on A do not know the language of people residing on place B
and vice-versa which we will be going to map with technical terms to discuss out major components inside the
JDBC.
• Mapping the same with technological terms to illustrate above real illustration. Here place A is
referred to as a java application and place B is therefore referred to as a database.
• Now the translator as discussed above which is responsible for converting java application calls
to database calls and database calls to java application calls is nothing but a ‘Driver Software’.
• The road between applications is ‘Connection’ and lastly the vehicle is our ‘statement object’.
• Now ‘requirement’ above is our SQL query and the ‘small block’ generated after processing the
SQL statement by the database engine has been passed in nothing but ‘ResultSet’. Now, this
technology by which java applications is communicating with database is ‘Java Database
Connectivity.
• By now we are done with a crystal clear overview of JDBC and geek you will be surprised that we
already have covered it, let dig down to get to know the working of components which will be
described up to greater depth in the environment setup of JDBC.
• Now we will penetrate down into the JDBC component which as discussed above is a technology
that is used to connect Java applications with the database. It is an API consisting of lots of
classes and interfaces by which with the help of some classes and interfaces we are able to
connect the java application to the database as pictorially depicted above. It has mainly two
packages namely as follows: java.sql package and javax.sql package.
JDBC API
JDBC API
• The Java Database Connectivity (JDBC) API is a Java-based API that enables interaction with relational
databases. JDBC provides a set of classes and interfaces to handle database operations such as
connecting to the database, executing queries, and managing results.
The JDBC API is comprised of two packages:
• java.sql: The core JDBC API package
• javax.sql: The JDBC Optional Package API, which extends the functionality of the JDBC API from client-side
to server-side
1. DriverManager
2. Connection (Interface):
3. Statement (Interface):
4. PreparedStatement (Interface):
5. ResultSet (Interface):
6. CallableStatement (Interface):
7. SQLException (Class):
It is an API consisting of lots of classes and interfaces by which with the
help of some classes and interfaces we are able to connect the java
application to the database.
It has mainly two packages namely as follows:
1. java.sql package and
2. javax.sql package.
Below is an explanation of the main JDBC classes and interfaces, their methods, and typical usage.
Interfaces and Classes of JDBC API: Some popular interfaces of JDBC API are listed below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
Some important Classes of JDBC API are listed below:
• DriverManager class
• Blob class
• Clob class
• Types class
1. DriverManager: used to Manages a list of database drivers.
Methods:
• static Connection getConnection(String url): Establishes a connection to the database.
• static Connection getConnection(String url, String user, String password): Establishes a
connection using the given URL, username, and password.
• static void registerDriver(Driver driver): Registers a driver with DriverManager.
Usage:
Usage:
Usage:
Usage:
Usage:
Usage:
Usage:
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
Establish a JDBC Connection
Step-by-Step Procedure to
Establish a JDBC Connection
1. Add JDBC driver to the classpath.
2. (Optional) Load the driver using Class.forName().
3. Establish a connection to the database using
DriverManager.getConnection().
4. Create a Statement or PreparedStatement for executing queries.
5. Execute the query using executeQuery() or executeUpdate().
6. Process the ResultSet (for SELECT queries).
7. Close the resources (Connection, Statement, ResultSet).
Step 1: Add JDBC Driver to the Classpath
The first step is to add the JDBC driver for the database you are using to the
classpath. The JDBC driver is required for Java to interact with the specific database.
The driver is typically provided as a .jar file.
You can add the driver in your project’s classpath or dependency manager (e.g.,
Maven or Gradle) by including it.
Step 2: Load the JDBC Driver (Optional)
In modern JDBC versions (Java 6 and above), loading the JDBC driver is
automatically handled by the DriverManager, so this step can be skipped in most
cases. However, for older JDBC versionas, you'll need to explicitly load the driver
using Class.forName().
Class.forName("com.mysql.cj.jdbc.Driver");
1. Using Statement:
Statement stmt = conn.createStatement();
2. Using PreparedStatement:
For more secure and optimized queries, use PreparedStatement when dealing with
parameterized SQL queries.
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
Step 7: Close the Resources
After the operations are complete, always close the ResultSet,
Statement, and Connection objects to free up resources.
rs.close();
stmt.close();
conn.close();
import java.sql.SQLException;
try{
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement(UPDATE_QUERY);
The programming involved to establish a JDBC connection is fairly simple. Here are these simple four
steps −
a. Import JDBC Packages − Add import statements to your Java program to import required
classes in your Java code.
b. Register(Load) JDBC Driver − This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
c. Database URL Formulation − This is to create a properly formatted address that points to the
database to which you wish to connect.
d. Create Connection Object − Finally, code a call to the DriverManager object's getConnection( )
method to establish actual database connection.
a. Import JDBC Packages
The Import statements tell the Java compiler where to find the classes
you reference in your code and are placed at the very beginning of your
source code.
To use the standard JDBC package, which allows you to select, insert,
update, and delete data in SQL tables, add the following imports to
your source code −
Here each form requires a database URL. A database URL is an address that
points to your database.
• To ensure that a connection is closed, you could provide a 'finally' block in your code.
A finally block always executes, regardless of an exception occurs or not.
• To close the above opened connection, you should call close() method as follows −
conn.close();
JDBC –
a. Statements,
b. PreparedStatement and
c. CallableStatement
JDBC - Statements, PreparedStatement and
CallableStatement
Once a connection is obtained we can interact with the database. The
JDBC Statement, CallableStatement, and PreparedStatement interfaces
define the methods and properties that enable you to send SQL or
PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences
between Java and SQL data types used in a database.
Once you've created a Statement object, you can then use it to execute an SQL
statement with one of its three execute methods.
1. boolean execute (String SQL): Returns a boolean value of true if a ResultSet object
can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL
statements or when you need to use truly dynamic SQL.
2. int executeUpdate (String SQL) − Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for which
you expect to get a number of rows affected - for example, an INSERT, UPDATE, or
DELETE statement.
3. ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.
Closing Statement Object
Just as you close a Connection object to save database resources, for
the same reason you should also close the Statement object.
A simple call to the close() method will do the job. If you close the
Connection object first, it will close the Statement object as well.
However, you should always explicitly close the Statement object to
ensure proper cleanup.
finally {
stmt.close();
}
JDBC Program Using Statement Object
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
while(rs.next())
{
System.out.println(rs.getInt('studentid'));
System.out.println(rs.getString("stuname"));
System.out.println(rs.getFloat("stumarks"));
}
}
catch(SQLException e)
{
System.ou.println(e.getMessage());
}
b. The PreparedStatement
b. The PreparedStatement Objects
• A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of Statement. Prepared Statement
objects have some useful additional features than Statement objects. Instead of hard coding queries,
PreparedStatement object provides a feature to execute a parameterized query .This statement gives you the
flexibility of supplying arguments dynamically.
myStmt.setInt(1,10);
myStmt.setString(2,"Chhavi");
4. Execute the Query
ResultSet myRs= myStmt.executeQuery();
• All parameters in JDBC are represented by the ? symbol, which is known as the
parameter marker. You must supply values for every parameter before executing the
SQL statement.
• The setXXX() methods bind values to the parameters, where XXX represents the Java
data type of the value you wish to bind to the input parameter. If you forget to supply
the values, you will receive an SQLException.
• Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java
array indices, which starts at 0.
• All of the Statement object's methods for interacting with the database (a) execute(),
(b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement
object. However, the methods are modified to use SQL statements that can input the
parameters.
Methods of PreparedStatement:
• setInt(int, int): This method can be used to set integer value at the given
parameter index.
• setString(int, string): This method can be used to set string value at the given
parameter index.
• setFloat(int, float): This method can be used to set float value at the given
parameter index.
• setDouble(int, double): This method can be used to set a double value at the
given parameter index.
• executeUpdate(): This method can be used to create, drop, insert, update, delete
etc. It returns int type.
• executeQuery(): It returns an instance of ResultSet when a select query is
executed.
Closing PreparedStatement Object
call to the close() ,close the PreparedStatement object. If you close the
Connection object first, it will close the PreparedStatement object as well.
explicitly close the PreparedStatement object to ensure proper cleanup.
finally {
pstmt.close();
}
executeQuery() Example using select statement:
import java.sql.*;
// Driver Code
public static void main(String[] args) throws Exception
{
// Prepare Statement
PreparedStatement myStmt = con.prepareStatement(query);
// Set Parameters
myStmt.setInt(1, 20);
myStmt.setString(2, 'Prateek');
executeUpdate() Example using insert query:
// Java program to update a table using PreparedStatement
import java.sql.*;
// Driver Code
public static void main(String[] args) throws Exception
{
// Prepare Statement
PreparedStatement myStmt= con.prepareStatement(query);
// Set Parameters
myStmt.setInt(1, 21);
myStmt.setString(2, 'Prajjwal');
executeUpdate() Example using update query:
import java.sql.*;
try{
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
PreparedStatement pstmt = conn.prepareStatement("UPDATE employees set first=? WHERE id=?");
try{
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement(UPDATE_QUERY);
A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
try{
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement(QUERY);
// Let us select all the records and display them.
ResultSet rs = pstmt.executeQuery(QUERY);
In JDBC, transactions help ensure ACID properties (Atomicity, Consistency, Isolation, Durability) to
maintain data integrity during operations like inserting, updating, or deleting data.
ACID Properties
Atomicity: All operations in a transaction either complete successfully or have no effect at all.
Consistency: A transaction takes the database from one consistent state to another.
Isolation: Transactions are isolated from each other, meaning the changes made in one transaction are
not visible to others until the transaction is committed.
Durability: Once a transaction is committed, its changes are permanent, even if the system crashes.
Benefits of Transaction Management in JDBC:
Method Description
That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-
commit and manage your own transactions −
1. To increase performance.
2. To maintain the integrity of business processes.
3. To use distributed transactions.
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn
off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);
Commit & Rollback
Once you are done with your changes and you want to commit the
changes then call commit() method on connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the
Connection named conn, use the following code −
conn.rollback( );
The following example illustrates the use of a commit and rollback object −
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
Example of transaction management in jdbc using Statement
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
If you see the table emp400, you will see that 2 records has been added.
Example of transaction management in jdbc using PreparedStatement
import java.sql.*;
import java.io.*;
class TM{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
Java Code to Read User Input and Store into Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
Create the MySQL Table
public class StoreLoginDetails {
CREATE DATABASE userdb;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); USE userdb;