0% found this document useful (0 votes)
463 views25 pages

Introduction to JDBC Programming

Chapter 5 of the document covers JDBC (Java Database Connectivity) programming, detailing its architecture, types of JDBC drivers, major classes and interfaces, and how to create simple JDBC applications. It explains the components of JDBC, including the JDBC API, DriverManager, and various types of JDBC drivers, along with their advantages and disadvantages. Additionally, it provides examples of how to connect to a MySQL database and execute SQL queries using Statement, PreparedStatement, and CallableStatement.

Uploaded by

harshshahboob
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)
463 views25 pages

Introduction to JDBC Programming

Chapter 5 of the document covers JDBC (Java Database Connectivity) programming, detailing its architecture, types of JDBC drivers, major classes and interfaces, and how to create simple JDBC applications. It explains the components of JDBC, including the JDBC API, DriverManager, and various types of JDBC drivers, along with their advantages and disadvantages. Additionally, it provides examples of how to connect to a MySQL database and execute SQL queries using Statement, PreparedStatement, and CallableStatement.

Uploaded by

harshshahboob
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

Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

Topics:
1. JDBC Architecture
2. Types of JDBC Drivers
3. Introduction to major JDBC classes and interface
4. Creating Simple JDBC Application
5. Types of statement (Statement Interface, PreparedStatement, CallableStatement)
6. Exploring ResultSet Operation
7. Creating CRUD Application

 Define JDBC

JDBC (Java Database Connectivity) is an API (Application Programming Interface) 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.

1
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

 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

 [Link]: 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

 [Link]: This package is the part of Java Enterprise Edition (Java EE)
, which extends the capabilities of [Link] 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.

2
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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 (Open Database Connectivity) 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.

Types of JDBC Drivers

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 [Link] and [Link].

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

3
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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 (Open Database Connectivity) 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.
4
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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)

5
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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.

Introduction to major JDBC classes and interface

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.

Precompiled SQL statement, used for dynamic queries with


PreparedStatement
parameters.

6
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

Class/Interfaces Description

CallableStatement Used to execute stored procedures in the database.

Represents the result set of a query, allowing navigation


ResultSet
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
[Link](“[Link]”);

Step 2: Establish a Connection


Connection connection = [Link](
“jdbc:mysql://localhost:3306/your_database”,
“your_username”,
“your_password”
);

Step 3: Create a Statement


Statement statement = [Link]();

Step 4: Execute a Query


String query = “INSERT INTO students (id, name) VALUES (101, ‘John Doe’)”;
int rowsAffected = [Link](query);
[Link](“Rows affected: ” + rowsAffected);

Step 5: Close the Connection


[Link]();
[Link]();

Creating 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 [Link].*;

public class Geeks {


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

// Replace with your database name


7
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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
[Link]("[Link]");

// Establish connection
Connection c = [Link](
url, username, password);

// Create a statement
Statement st = [Link]();

// Execute the query


int count = [Link](query);
[Link](
"Number of rows affected by this query: "
+ count);

// Close the connection


[Link]();
[Link]();
[Link]("Connection closed.");
}
catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: "
+ [Link]());
}
catch (SQLException e) {
[Link]("SQL Error: "
+ [Link]());
} }
}
Output:

8
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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.

Types of statement (Statement Interface, PreparedStatement,


CallableStatement)

In Java, the Statement interface in JDBC (Java Database Connectivity) is used to create
and execute SQL queries in Java applications. JDBC provides three types of statements to
interact with the database:

1. Statement
2. Prepared Statement
3. Callable Statement

9
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

1. Statement
A Statement object is used for general-purpose access to databases and is useful for
executing static SQL statements at runtime.
Syntax:
Statement statement = [Link]();

Implementation: Once the Statement object is created, there are three ways to execute it.

 execute(String SQL): It is used to executes any SQL statements (like SELECT,


INSERT, UPDATE or DELETE). If the ResultSet object is retrieved, then it returns true
else false is returned.

 executeUpdate(String SQL): It is used to executes SQL statements (like INSERT,


UPDATE or DELETE). It returns the number of rows affected by the SQL statement.

 ResultSet executeQuery(String SQL): It is used to executes the SELECT query. It


returns a ResultSet object that contains the data retrieved by the query.

Example:
// Java Program illustrating Create Statement in JDBC
import [Link].*;

public class Geeks {


public static void main(String[] args) {
try {

// Load the driver


[Link]("[Link]");

// Establish the connection


Connection con = [Link](
"jdbc:mysql://localhost:3306/world", "root", "12345");

// Create a statement
Statement st = [Link]();

// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = [Link](sql);

// Process the results


while ([Link]()) {
[Link]("Name: " + [Link]("name") +
", Age: " + [Link]("age"));
}

// Close resources
[Link]();
[Link]();
[Link]();
} catch (Exception e) {

10
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

[Link]();
}
}
}

Output: Name and age are as shown for random inputs.

2. Prepared Statement
A PreparedStatement represents a precompiled SQL statement that can be executed
multiple times. It accepts parameterized SQL queries, with ? as placeholders for
parameters, which can be set dynamically.

Illustration:
Considering in the people database if there is a need to INSERT some values, SQL
statements such as these are used:

INSERT INTO people VALUES (“Ayan”,25);


INSERT INTO people VALUES(“Kriya”,32);

To do the same in Java, one may use Prepared Statements and set the values in the ?
holders, setABC() of a prepared statement is used as shown:

String query = “INSERT INTO people(name, age)VALUES(?, ?)”;


PreparedStatement pstmt = [Link](query);
// where pstmt is an object name
[Link](1,”Ayan”);
[Link](2,25);

Implementation: Once the PreparedStatement object is created, there are three ways to
execute it:

 execute(): This returns a boolean value and executes a static SQL statement that is
present in the prepared statement object.

 executeQuery(): This returns a ResultSet from the current prepared statement.

11
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

 executeUpdate(): This returns the number of rows affected by the DML statements
such as INSERT, DELETE, and more that is present in the current Prepared Statement.
Example:
// Java Program illustrating Prepared Statement in JDBC
import [Link].*;

import [Link];

class Geeks {

public static void main(String[] args) {

// try block to check for exceptions


try {

// Loading drivers using forName() method


[Link]("[Link]");

// Scanner class to take input from user


Scanner sc = new Scanner([Link]);

[Link](
"What age do you want to search?? ");

// Reading age an primitive datatype from user


// using nextInt() method
int age = [Link]();

// Registering drivers using DriverManager


Connection con = [Link](
"jdbc:mysql:///world", "root", "12345");

// Create a statement
PreparedStatement ps = [Link](
"select name from [Link] where age = ?");

// Execute the query


[Link](1, age);
ResultSet res = [Link]();

// Condition check using next() method


// to check for element
while ([Link]()) {

// Print and display elements(Names)


[Link]("Name : "
+ [Link](1));
}

// Catch block to handle database exceptions


12
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

catch (SQLException e) {

// Display the DB exception if any


[Link](e);
}

// Catch block to handle class exceptions


catch (ClassNotFoundException e) {

// Print the line number where exception occurred


// using printStackTrace() method if any
[Link]();
}
}
}
Output:

3. Callable Statement
A CallableStatement is used to execute stored procedures in the database. Stored
procedures are precompiled SQL statements that can be called with parameters. They are
useful for executing complex operations that involve multiple SQL statements.

Syntax:
CallableStatement cstmt = [Link](“{call ProcedureName(?, ?)}”);
 {call ProcedureName(?, ?)}: Calls a stored procedure named ProcedureName with
placeholders ? for input parameters.

Methods to Execute:
 execute(): Executes the stored procedure and returns a boolean indicating whether the
result is a ResultSet (true) or an update count (false).

 executeQuery(): Executes a stored procedure that returns a ResultSet.

 executeUpdate(): Executes a stored procedure that performs an update and returns the
number of rows affected.

Example:
// Java Program illustrating
// Callable Statement in JDBC
import [Link].*;

public class Geeks {

public static void main(String[] args) {

13
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

// Try block to check if any exceptions occur


try {

// Load and register the driver


[Link]("[Link]");

// Establish a connection
Connection con = DriverManager
.getConnection("jdbc:mysql:///world", "root", "12345");

// Create a CallableStatement
CallableStatement cs =
[Link]("{call GetPeopleInfo()}");

// Execute the stored procedure


ResultSet res = [Link]();

// Process the results


while ([Link]()) {

// Print and display elements (Name and Age)


[Link]("Name : " + [Link]("name"));
[Link]("Age : " + [Link]("age"));
}

// Close resources
[Link]();
[Link]();
[Link]();
}
// Catch block for SQL exceptions
catch (SQLException e) {
[Link]();
}
// Catch block for ClassNotFoundException
catch (ClassNotFoundException e) {
[Link]();
}
}
}
Output:

Explanation:
 This Java code demonstrates how to use a CallableStatement in JDBC to execute a
stored procedure.
14
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

 It connects to a MySQL database and prepares a CallableStatement to call a stored


procedure named peopleinfo with two parameters.

 After executing the procedure, it runs a SELECT query to retrieve and display all
records from the people table.

 Exception handling is included to manage potential SQL and class loading errors.

Exploring ResultSet Operation

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 = [Link](url, username, password);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM your_table");

while ([Link]()) {
// Process the result set
}

[Link]();
[Link]();
[Link]();
}
catch (SQLException e) {
[Link](); // Handle the exception
}

15
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

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.

16
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

Method Description

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

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 [Link]

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

getArray(int columnIndex) used for Retrieves a SQL array

17
Chapter: 5 JDBC Programming SYBCA Sem-4 Su
ub: IPWCT

iii). Updating Data in a ResultSet:


These methods allow you to update data in the Result.

Method Description

used for Updates an integer value in the specified


updateInt(int columnIndex, int x) column

updateString(int columnIndex, String


used for Updates a string value
x)

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

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 demo;
import [Link];
import [Link]
[Link];
import [Link]
[Link];
import [Link];
import [Link];
import [Link];

public class JDBCOperations {

// Establish database connection


private static Connection getConnection
getConnection()
18
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

throws Exception {

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


String jdbcUser = "root";
String jdbcPassword = "password";

return [Link](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
= [Link](query);
[Link](1, name);
[Link](2, salary);
[Link]();

[Link]("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
= [Link](query);
[Link](1, name);
[Link](2, salary);
[Link](3, id);
[Link]();

[Link]("Record updated successfully.");


}

// Retrieve records from the database


private static void
retrieveRecords(Connection connection) throws Exception {
Statement statement = [Link]();
ResultSet resultSet = [Link]("SELECT * FROM employees");

[Link]("Records in the database:");


while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
19
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

double salary = [Link]("salary");


[Link]("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
= [Link](query);
[Link](1, id);
[Link]();
[Link]("Record deleted successfully.");
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
try {
Connection connection = getConnection();

[Link]("Select an operation:");
[Link]("1. Insert");
[Link]("2. Update");
[Link]("3. Retrieve");
[Link]("4. Delete");

int choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter name:");

String nameToInsert = [Link]();


[Link]("Enter salary:");
double salaryToInsert = [Link]();
insertRecord(connection, nameToInsert,
salaryToInsert);
break;

case 2:
[Link]("Enter ID to update:");
int idToUpdate = [Link]();
[Link]("Enter new name:");
String nameToUpdate = [Link]();
[Link]("Enter new salary:");
double salaryToUpdate
= [Link]();
updateRecord(connection, idToUpdate,
20
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

nameToUpdate, salaryToUpdate);
break;

case 3:
retrieveRecords(connection);
break;

case 4:
[Link]("Enter ID to delete:");
int idToDelete = [Link]();
deleteRecord(connection, idToDelete);
break;

default:
[Link]("Invalid choice.");
break;
}

// Close the connection at the end


[Link]();
} catch (Exception e) {
[Link]();
} finally {
[Link]();
}
}
}

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.
21
Chapter: 5 JDBC Programming SYBCA Sem-4 Su
ub: IPWCT

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.

22
Chapter: 5 JDBC Programming SYBCA Sem-4 Su
ub: IPWCT

Now enter option 4, That means you can delete an employee details by using employee ID.

Creating CRUD Application

Creating, reading, updating, and deleting data in a database is a common task in many
applications, and JDBC (Java Database Connectivity) is a Java API that allows you to
connect to a database and perform these operations. In this blog post, we will walk through
the steps of setting up a simple CRUD (create, read, update, delete) operation using JDBC.

1. Connect to the database


The first step iss to establish a connection to the database. You can do this by loading the
JDBC driver and creating a connection object.

 Java code
try
{
[Link]("[Link]");
Connection con = [Link]( "jdbc:
"jdbc:mysql://localhost:3306/mydb
mysql://localhost:3306/mydb",
"username", "password");
[Link]("Connection established.");
}
catch (Exception e) {
[Link]();
}

23
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

2. Create a new record


Once you have a connection to the database, you can use the connection object to create a
new record in the database. To do this, you will need to use an SQL INSERT statement and
execute it using the connection object.

 Java code
try {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = [Link](sql);
[Link](1, "value1");
[Link](2, "value2");
[Link](3, 123);
[Link]();
[Link]("Record created.");
} catch (SQLException e) {
[Link]();
}

3. Read a record

To read a record from the database, you will need to use an SQL SELECT statement and
execute it using the connection object. The result of the query will be a ResultSet object
that you can use to access the data in the record.

 Java code
try {
String sql = "SELECT column1, column2, column3 FROM table_name WHERE id = ?";
PreparedStatement statement = [Link](sql);
[Link](1, 1);
ResultSet result = [Link]();
if ([Link]()) {
String column1 = [Link]("column1");
String column2 = [Link]("column2");
int column3 = [Link]("column3");
[Link]("Column 1: " + column1);
[Link]("Column 2: " + column2);
[Link]("Column 3: " + column3);
}
} catch (SQLException e) {
[Link]();
}

24
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

4. Update a record
To update a record in the database, you will need to use an SQL UPDATE statement and
execute it using the connection object.

 Java code
try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ? WHERE id =
?";
PreparedStatement statement = [Link](sql);
[Link](1, "new_value1");
[Link](2, "new_value2");
[Link](3, 456);
[Link](4, 1);
[Link]();
[Link]("Record updated.");
} catch (SQLException e) {
[Link]();
}

5. Delete a record
To delete a record from the database, you will need to use an SQL DELETE statement and
execute it using the connection object.

 Java code
try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = [Link](sql);
[Link](1, 1);
[Link]();
[Link]("Record deleted.");
} catch (SQLException e) {
[Link]();
}

25

Common questions

Powered by AI

Type-3 JDBC drivers, known as Network Protocol drivers, are fully written in Java and utilize a middleware application server to convert JDBC calls into vendor-specific database protocol. They are portable due to being Java-based and do not require any client-side library as the middleware manages tasks like load balancing and auditing. However, they require network support on the client machine and may have higher maintenance costs due to middle-tier coding needs. Type-4 JDBC drivers, or Thin drivers, also fully Java-based, communicate directly with the database without needing a middleware server or native libraries, which simplifies deployment and enhances performance. They are ideal for single-database scenarios because no additional libraries or installations are required. Each has its advantages, with Type-3 being ideal for situations involving multiple databases and Type-4 being optimal for dedicated single-database applications .

PreparedStatement improves performance in JDBC applications by allowing SQL statements to be precompiled and stored, which means they can be executed multiple times with different input parameters without the need for recompilation. This reduces execution time, particularly for complex queries or operations executed repeatedly. CallableStatement further enhances performance by allowing the execution of stored procedures, which are precompiled and efficient for complex operations involving multiple SQL statements. Both PreparedStatement and CallableStatement allow for parameterized queries, reducing the chance for SQL injection and improving security and maintainability of code compared to standard Statement, which handles static SQL and recalibrates the query every time it is executed .

When using a CallableStatement in a JDBC application, factors to consider include the need for stored procedure parameters, which must be correctly defined and bound to the statement. The developer must ensure the database supports these procedures and that they are properly compiled in the database schema. CallableStatements offer advantages for executing complex operations involving multiple SQL statements within a single call, which can enhance performance but require careful management of input and output parameters. Handling exceptions and managing transactions associated with these procedures must also be carefully implemented to ensure robustness and data integrity .

When selecting a JDBC driver type for a Java application that needs to work with Oracle and MySQL databases, a key consideration is the need for flexibility and efficiency in database interactions. Type-4 drivers would be most suitable for applications dedicated to a particular database, due to their direct database interaction and lack of middleware requirements, offering high performance for specific databases. Meanwhile, if the application needs to switch between Oracle and MySQL or support connectivity for multiple databases concurrently, Type-3 drivers are preferable due to their ability to manage multiple database connections via middleware, without needing individual client-side setups. Considerations include the complexity of deployment, performance requirements, and potential need for cross-database functionalities .

The SQLException class in JDBC is critical for handling errors that occur during interactions with the database. It helps developers understand what went wrong in database operations by providing detailed descriptions and codes corresponding to errors. SQLException can provide a chain of exceptions that might occur when executing a series of database operations, which is crucial for debugging and maintaining the integrity of the application. It allows for implementing robust error-handling strategies to ensure that applications can recover gracefully from database-related errors, providing a smoother user experience and preventing data corruption or loss .

The JDBC DriverManager plays a critical role in the JDBC architecture by managing the connection between the Java application and the database. It loads the database-specific driver that is necessary to establish a connection with the database, thus facilitating database operations. The DriverManager ensures that the correct driver is used to process user requests and interact with the database effectively. It acts as a fundamental component that manages available drivers and establishes the database connectivity required for executing queries and handling transactions .

JDBC facilitates batch processing by allowing multiple SQL statements to be grouped together and executed in a single database call. This reduces the number of round-trips between the application and the database, enhancing performance. Developers can use methods like addBatch() and executeBatch() on Statement or PreparedStatement objects to manage batch processing efficiently. Connection pooling complements batch processing by managing a pool of database connections, reducing the overhead of establishing and closing connections repeatedly. This combination results in faster execution times and can substantially enhance the throughput of database operations in resource-intensive applications .

The Type-1 JDBC driver, also known as the JDBC-ODBC Bridge Driver, has several advantages including being built into JDK, which eliminates the need for separate installations, and its ability to connect to any database, making it database-independent. However, it has distinct disadvantages such as the need for the ODBC bridge to be installed on individual client machines and security vulnerabilities due to common driver usage. Additionally, since it is not written in Java, it lacks portability. This driver is typically not used for deployment due to its limitations and is generally suited for development and testing purposes when flexibility and simplicity are priorities .

The ResultSet interface in JDBC enables data manipulation and retrieval by acting as a cursor to navigate through the rows of data returned by a SQL query. It provides methods like next(), previous(), first(), and last() to move the cursor and access data sequentially or randomly. The ResultSet allows developers to retrieve specific columns using methods such as getString(), getInt(), and getDouble() to extract data of different types. This interface is a key component of JDBC that helps interact dynamically with query results, offering flexibility in how data is processed, manipulated, and presented within Java applications .

A developer might choose the Network Protocol driver (Type-3) in a multi-database environment due to its portability and lack of requirement for client-side installations. It handles database connectivity through a middleware server, which enables managing multiple types of database connections efficiently. Since the driver is written fully in Java, it is portable across different platforms. The middleware can provide additional functionalities like load balancing and auditing, adding layers of flexibility and capability in managing diverse needs. This makes Type-3 particularly appealing for applications that need to switch between databases or support various database backends seamlessly .

You might also like