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

JDBC

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

JDBC

JDBC NOtes
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 120

UNIT-III: WORKING

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 is platform-independent, and is used by Java developers to interact with databases


in a simple and efficient way.
Usecases:
• Web applications: E-commerce, social media.
• Enterprise systems: ERP, CRM.
• Desktop applications: Inventory systems, library management.
• Mobile applications: Java ME apps.
• Data migration/ETL: Moving data between databases.
• Reporting/analytics: Business reports, data visualization.
• Middleware/API: RESTful services, API layers.
• Distributed systems: Microservices.
• Testing: Automated tests for SQL queries.
• Real-time data processing: Stock trading platforms, real-time monitoring.

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.

3. DriverManager: DriverManager class in the JDBC architecture is used to establish a connection


between Java applications and databases. Using the getConnection method of this class a
connection is established between the Java application and data sources.

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.*;

2. JDBC Driver Manager


JDBC DriverManager is a class in JDBC API that loads a database-specific driver
in Java application and establishes a connection with a database.
DriverManager makes a call to a specific database to process the user request.
3. JDBC Test Suite
JDBC Test Suite is used to test operations being performed on databases using
JDBC drivers. JDBC Test Suite tests operations such as insertion, updating, and
deletion.

4. JDBC-ODBC Bridge Drivers


As the name suggests JDBC-ODBC Bridge Drivers are used to translate JDBC
methods to ODBC function calls. JDBC-ODBC Bridge Drivers are used to connect
database drivers to the database. Even after using JDBC for Java Enterprise
Applications, we need an ODBC connection for connecting with databases.

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:

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
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.
• JDBC drivers are the software components which implements interfaces in JDBC APIs to
enable java application to interact with the database.
• There are four types of JDBC drivers defined by Sun Microsystem that are mentioned
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
• Type 1 driver are database
independent and platform dependent.
• Type 2 driver are database dependent
and platform dependent.
• Type 3 driver are database
independent and platform
independent.
• Type 4 driver are database dependent
and platform independent.
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.

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

• 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 varies, then the driver will carry because it is database
dependent.
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.
import java.sql.*;

public class JDBCEx {

public static void main(String args[])


{
Connection con = null;
Statement st = null;

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:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",


"password");
2. Connection (Interface): Represents a connection to a specific database.
 Methods:
• Statement createStatement(): Creates a Statement object for executing SQL queries.
• PreparedStatement prepareStatement(String sql): Creates a PreparedStatement object for
precompiled SQL.
• void setAutoCommit(boolean autoCommit): Turns transaction auto-commit on or off.
• void commit(): Commits the current transaction.
• void rollback(): Rolls back the current transaction.
• void close(): Closes the connection.

Usage:

• Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",


"password");
• conn.setAutoCommit(false);
• conn.commit();
• conn.close();
3. Statement (Interface): Used to execute SQL queries against the
database.
 Methods:
ResultSet executeQuery(String sql): Executes a SQL query and returns the result as a
ResultSet.
int executeUpdate(String sql): Executes an update operation (like INSERT, UPDATE,
DELETE) and returns the number of affected rows.
boolean execute(String sql): Executes any SQL statement (query or update).
void close(): Closes the statement.

Usage:

• Statement stmt = conn.createStatement();


• ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
• stmt.close();
4. PreparedStatement (Interface): Represents a precompiled
SQL statement that can be executed multiple times with different parameters.
 Methods:
• void setInt(int parameterIndex, int value): Sets an integer parameter.
• void setString(int parameterIndex, String value): Sets a string parameter.
• ResultSet executeQuery(): Executes the SQL query.
• int executeUpdate(): Executes an update operation.

Usage:

• PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM employees


WHERE id = ?");
• pstmt.setInt(1, 101);
• ResultSet rs = pstmt.executeQuery();
• pstmt.close();
5. ResultSet (Interface): Represents the result set of a SQL query.
 Methods:
• boolean next(): Moves the cursor to the next row of the result set.
• int getInt(String columnLabel): Retrieves an integer value from the specified column.
• String getString(String columnLabel): Retrieves a string value from the specified column.
• boolean getBoolean(String columnLabel): Retrieves a boolean value.
• void close(): Closes the result set.

Usage:

ResultSet rs = stmt.executeQuery("SELECT * FROM employees");


while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
}
rs.close();
6. CallableStatement (Interface): Used to execute stored procedures in the
database.
 Methods:
• void registerOutParameter(int parameterIndex, int sqlType): Registers an output parameter.
• void setInt(int parameterIndex, int value): Sets an integer parameter.
• void setString(int parameterIndex, String value): Sets a string parameter.
• boolean execute(): Executes the stored procedure.
• int getInt(int parameterIndex): Retrieves an integer output parameter.

Usage:

CallableStatement cstmt = conn.prepareCall("{call getEmployeeName(?, ?)}");


cstmt.setInt(1, 101);
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.execute();
String name = cstmt.getString(2);
cstmt.close();
7. SQLException (Class): Represents an error or exception that occurs during
JDBC operations.
Methods:
• String getMessage(): Retrieves the error message.
• String getSQLState(): Retrieves the SQL state code.
• int getErrorCode(): Retrieves the vendor-specific error code.

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.

• For MySQL, the driver is mysql-connector-java.jar.


• For PostgreSQL, the driver is postgresql.jar.

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");

This loads the MySQL JDBC driver class into memory.


Step 3: Establish a Connection to the Database
To connect to the database, you need to use DriverManager.getConnection(). This method returns a
Connection object, which represents the connection to the database.
1. JDBC URL
The connection URL is essential for the DriverManager to identify the database. The format of the URL varies
depending on the database you're using. The URL contains the protocol (jdbc), the subprotocol (specific to
the database, e.g., mysql, postgresql), and the database details.
String url = "jdbc:mysql://localhost:3306/mydatabase";
2. Username and Password
You also need to provide the username and password for authentication to the database.
3. Get Connection
Connection conn = DriverManager.getConnection(url, "username", "password");

Example for MySQL:


String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
Step 4: Create a Statement
Once a connection is established, you can create a Statement or PreparedStatement to
execute SQL queries.

1. Using Statement:
Statement stmt = conn.createStatement();

2. Using PreparedStatement:
For more secure and optimized queries, use PreparedStatement when dealing with
parameterized SQL queries.

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM employees


WHERE id = ?");
pstmt.setInt(1, 101);
Step 5: Execute the Query
Execute SQL queries using the executeQuery() method for SELECT statements or
executeUpdate() for INSERT, UPDATE, DELETE operations.

1. Executing a SELECT Query:

ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

2. Executing an Update Query (e.g., INSERT, UPDATE, DELETE):

int rowsAffected = stmt.executeUpdate("INSERT INTO employees (name)


VALUES ('John')");
Step 6: Process the Result
If you are executing a SELECT query, the result is stored in a ResultSet
object. You can iterate through the ResultSet to retrieve the data.

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;

public class JDBCPreparedStatementExample {


static final String DB_URL = "jdbc:mysql://localhost:3306/studentdb";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT StudentID, LastName, FirstName, Dept FROM Students";
static final String UPDATE_QUERY = "UPDATE Students set Dept=? WHERE studentid=?";

public static void main(String[] args) {

try{
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement(UPDATE_QUERY);

// Bind values into the parameters.


pstmt.setString(1, "Mathematics");
pstmt.setInt(2, 1000);

// Updating Dept of the record with StudentID = 1000


int rows = pstmt.executeUpdate();
System.out.println("Rows impacted : " + rows );
JDBC - Database Connections
JDBC - Database Connections
After you've installed the appropriate driver, it is time to establish a database connection using JDBC.

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 −

import java.sql.* ; // for standard JDBC programs


import java.math.* ; // for BigDecimal and BigInteger support
b. Register JDBC Driver
You must register the driver in your program before you use it. Registering the driver is the process by which the
Oracle driver's class file is loaded into the memory, so it can be utilized as an implementation of the JDBC
interfaces.

You need to do this registration only once in your program.


• Class.forName()
The most common approach to register a driver is to use Java's Class.forName() method, to dynamically load the
driver's class file into memory, which automatically registers it. This method is preferable because it allows you
to make the driver registration configurable and portable.

example uses Class.forName( ) to register the Oracle driver −


try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
c. Database URL Formulation
After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method.
• getConnection(String url)
• getConnection(String url, Properties prop)
• getConnection(String url, String user, String password)

Here each form requires a database URL. A database URL is an address that
points to your database.

Formulating a database URL is where most of the problems associated with


establishing a connection occurs.
Following table lists down the popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format


MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName
jdbc:oracle:thin:@hostname:port
ORACLE oracle.jdbc.driver.OracleDriver
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName
d. Create Connection Object
We have listed down three forms of DriverManager.getConnection() method to create a connection
object.
 Using a Database URL with a username and password
• The most commonly used form of getConnection() requires you to pass a database URL, a username,
and a password −
• Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the
database portion of the URL.
• If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener is
configured to listen on port 1521, and your database name is EMP, then complete database URL would
be −
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and password to get a
Connection object as follows −

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";


String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
e. Closing JDBC Connections
• At the end of your JDBC program, it is required explicitly to close all the connections
to the database to end each database session. However, if you forget, Java's garbage
collector will close the connection when it cleans up stale objects.

• Relying on the garbage collection, especially in database programming, is a very poor


programming practice. You should make a habit of always closing the connection
with the close() method associated with connection object.

• 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.

The following table provides a summary of each interface's purpose to


decide on the interface to use.
Interfaces Recommended Use
Use this for general-purpose access to your database.
Statement Useful when you are using static SQL statements at
runtime. The Statement interface cannot accept
parameters.
Use this when you plan to use the SQL statements many
PreparedStatement times. The PreparedStatement interface accepts input
parameters at runtime.
Use this when you want to access the database stored
CallableStatement procedures. The CallableStatement interface can also
accept runtime input parameters.
a. Statement
a. Statement Objects
Creating Statement Object: Before you can use a Statement object to execute a SQL
statement, you need to create one using the Connection object's createStatement( ) method,
as in the following example −

Statement stmt = null;


try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
...
}
Statement Object Methods:

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;

public class JDBCStatementExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
static final String UPDATE_QUERY = "UPDATE Employees set age=30 WHERE id=103";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
// Let us check if it returns a true Result Set or not.
Boolean ret = stmt.execute(UPDATE_QUERY);
System.out.println("Return value is : " + ret.toString() );

// Let us update age of the record with ID = 103;


Delete Example by statement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT StudentID, LastName, FirstName, Address, Dept FROM Students";
static final String DELETE_QUERY = "DELETE FROM Students WHERE StudentID='1005'";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
//Check if it returns a true Result Set or not.
boolean ret = stmt.execute(DELETE_QUERY);

// Insert a new record;


int rows = stmt.executeUpdate(DELETE_QUERY);
Slect query example:
import java.sql.*;
public class Example{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.cj.jdbc.driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select studentid,stuname,stumarks from student");

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.

Creating PreparedStatement Object


PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
Advantages of PreparedStatement

• When PreparedStatement is created, the SQL query is passed as a


parameter. This Prepared Statement contains a pre-compiled SQL
query, so when the PreparedStatement is executed, DBMS can just run
the query instead of first compiling it.
• We can use the same PreparedStatement and supply with different
parameters at the time of execution.
• An important advantage of PreparedStatements is that they prevent
SQL injection attacks
Steps to use PreparedStatement
1. Create Connection to Database

Connection myCon = DriverManager.getConnection(path,username,password)


2. Prepare Statement

select * from students where age> ? and name = ?


PreparedStatement myStmt;
myStmt = myCon.prepareStatement(select * from students where age> ? and name = ?);

3. Set parameter values for type and position

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.*;

public class Example {

// Driver Code
public static void main(String[] args) throws Exception
{

// Connection to your database


Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

// Query which needs parameters


String query = "Select * from students where age> ? and name = ?";

// 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.*;

public class GFG {

// Driver Code
public static void main(String[] args) throws Exception
{

// Connection to your database


Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

// Query which needs parameters


String query = "insert into Students values(?,?)";

// 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.*;

public class Conn {


public static void main(String[] args) {

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=?");

// Bind values into the parameters.


pstmt.setString(1, "Sita");
pstmt.setInt(2, 100);

// Updating Dept of the record with StudentID = 1000


int rows = pstmt.executeUpdate();
System.out.println("Rows impacted : " + rows );
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
Prepared Statement Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCPreparedStatementExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
static final String UPDATE_QUERY = "UPDATE Employees set age=? WHERE id=?";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);
){
// Bind values into the parameters.
stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID

// Let us update age of the record with ID = 102;


import java.sql.SQLException;

public class JDBCPreparedStatementExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT StudentID, LastName, FirstName, Dept FROM Students";
static final String UPDATE_QUERY = "UPDATE Students set Dept=? WHERE studentid=?";

public static void main(String[] args) {

try{
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement(UPDATE_QUERY);

// Bind values into the parameters.


pstmt.setString(1, "Mathematics");
pstmt.setInt(2, 1000);

// Updating Dept of the record with StudentID = 1000


int rows = pstmt.executeUpdate();
System.out.println("Rows impacted : " + rows );
c. The CallableStatement Objects
Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database
stored procedure.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
JDBC - Result Sets
JDBC - Result Sets
The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result set.
The java.sql.ResultSet interface represents the result set of a database 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 −

1. Navigational methods − Used to move the cursor around.


2. Get methods − Used to view the data in the columns of the current row being pointed by the
cursor.
3. Update methods − Used to update the data in the columns of the current row. The updates can
then be updated in the underlying database as well.
Steps to Create and Use a ResultSet

1. Establish a Connection to the database.


2. Create a Statement object (e.g., Statement or PreparedStatement).
3. Execute a Query: Use the executeQuery() method to run a SELECT
statement and obtain a ResultSet object.
4. Process the ResultSet: Use the next() method to iterate through the rows
in the ResultSet and retrieve column values using appropriate getter
methods.
5. Close the ResultSet and other resources (e.g., Statement, Connection).
Common Use Cases of ResultSet:
• Retrieving and displaying query results from a database.
• Navigating through result sets (e.g., moving forward or backward in a
set of results).
• Extracting specific rows or columns based on conditions.
• Performing updates directly on the database through updatable result
sets.
Methods of ResultSet
1. Navigation Methods:

• next(): Moves to the next row.


• previous(): Moves to the previous row (only for scrollable ResultSet).
• first(): Moves to the first row.
• last(): Moves to the last row.
• absolute(int row): Moves to a specific row number.
• relative(int row): Moves the cursor by the specified number of rows forward
or backward.
2. Get Methods
Get methods are used to retrieve the value of a column from the current row in the ResultSet. These
methods are available for each data type, such as String, int, double, boolean, etc.

Common Get Methods


• getString(): Retrieves a String value.
• getInt(): Retrieves an int value.
• getBoolean(): Retrieves a boolean value.
• getDouble(): Retrieves a double value.
• getDate(): Retrieves a java.sql.Date value.
• You can specify the column by either the column index (starting from 1) or the column label (the
column name as defined in the SQL query).
Syntax:

• String value = rs.getString(columnLabel); // By column label (e.g., "name")


• int value = rs.getInt(columnIndex); // By column index (e.g., 1)
ResultSet rs = pstmt.executeQuery(QUERY);

// Extract data from result set


while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("StudentID"));
System.out.print(", LastName: " + rs.getString("LastName"));
System.out.print(", FirstName: " + rs.getString("FirstName"));
System.out.println(", Dept: " + rs.getString("Dept"));
}
rs.close();
pstmt.close();
3. Update Methods
Update methods are used to modify the values in the current row of an
updatable ResultSet. An updatable ResultSet allows you to update the rows
in the database directly through the ResultSet. After updating the values,
you can call updateRow() to commit the changes to the database.
Common Update Methods
updateString(): Updates a String value.
updateInt(): Updates an int value.
updateBoolean(): Updates a boolean value.
updateDouble(): Updates a double value.
updateDate(): Updates a Date value.
Like get methods, you can specify the column either by index or by label.
Syntax

rs.updateString(columnLabel, newValue); // Update by column label


rs.updateInt(columnIndex, newValue); // Update by column index
rs.updateRow(); // Commit the updates to the database
import java.sql.SQLException;

public class JDBCPreparedStatementExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT StudentID, LastName, FirstName, Dept FROM Students";

public static void main(String[] args) {

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);

// Extract data from result set


while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("StudentID"));
System.out.print(", LastName: " + rs.getString("LastName"));
System.out.print(", FirstName: " + rs.getString("FirstName"));
System.out.println(", Dept: " + rs.getString("Dept"));
Transaction Management in
JDBC
Transaction Management in
JDBC
Transaction management in JDBC refers to the process of managing a series of database operations (SQL
queries) as a single, atomic unit of work. A transaction is a sequence of operations performed as a single
logical unit of work that either fully succeeds (all operations complete successfully) or fully fails (if any
operation fails, all changes are rolled back).

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:

Atomic Operations: Ensures that a group of operations is performed as a


single unit, improving data consistency.
Error Handling: By rolling back changes in case of errors, it prevents
incomplete or incorrect data from being committed to the database.
Data Integrity: Transactions maintain the integrity of data, ensuring that only
valid changes are saved.
Concurrency Control: Transactions help manage simultaneous access to the
database by isolating changes from other users until the transaction is
completed.
Common Use Cases:
• Banking Applications: Transferring money between accounts where
both debit and credit operations must succeed together.
• E-commerce Applications: Processing orders where the order
creation, payment, and inventory deduction must happen in a single
transaction.
• Batch Processing: Inserting or updating multiple records at once,
ensuring that partial data is not saved in case of failure.
In JDBC, Connection interface provides methods to manage transaction.

Method Description

It is true bydefault means each transaction is committed


void setAutoCommit(boolean status)
bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.

Creates a savepoint within a transaction, allowing partial


setSavepoint()
rollbacks.
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed
to the database upon its completion.

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);

PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


while(true){

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;

// Read user input from console CREATE TABLE logins (


System.out.print("Enter username: "); id INT AUTO_INCREMENT PRIMARY KEY,
String username = scanner.nextLine(); username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
System.out.print("Enter password: "); );
String password = scanner.nextLine();

// JDBC setup: database URL, username, and password


String jdbcURL = "jdbc:mysql://localhost:3306/userdb"; // Your MySQL URL
String dbUser = "root"; // Your MySQL username
String dbPassword = "password"; // Your MySQL password
End
8,,,33,34,,,,,,48,,,,,,le-3,4,6,33

You might also like