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

Chapter 5 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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Chapter 5 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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

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

 java.sql: This package, is the part of Java Standard Edition (Java SE)
, which contains the core interfaces and classes for accessing and processing data in
relational databases. It also provides essential functionalities like establishing
connections, executing queries, and handling result sets

 javax.sql: This package is the part of Java Enterprise Edition (Java EE)
, which extends the capabilities of java.sql by offering additional features like
connection pooling, statement pooling, and data source management.
It also provides a standard to connect a database to a client application.

2. JDBC Driver Manager


Driver manager is responsible for loading the correct database-specific driver to establish a
connection with the database. It manages the available drivers and ensures the right one is
used to process user requests and interact with the database.

3. JDBC Test Suite


It is used to test the operation(such as insertion, deletion, updating) being performed by
JDBC Drivers.

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 java.sql and javax.sql.

JDBC helps you to write Java applications that manage these three programming activities:

1. Connect to a data source, like a database.


2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query

Structure of JDBC Driver

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
Class.forName(“com.mysql.cj.jdbc.Driver”);

Step 2: Establish a Connection


Connection connection = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/your_database”,
“your_username”,
“your_password”
);

Step 3: Create a Statement


Statement statement = connection.createStatement();

Step 4: Execute a Query


String query = “INSERT INTO students (id, name) VALUES (101, ‘John Doe’)”;
int rowsAffected = statement.executeUpdate(query);
System.out.println(“Rows affected: ” + rowsAffected);

Step 5: Close the Connection


statement.close();
connection.close();

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

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
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
Connection c = DriverManager.getConnection(
url, username, password);

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

// Execute the query


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

// Close the connection


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

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 = connection.createStatement();

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

public class Geeks {


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

// Load the driver


Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


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

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

// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = st.executeQuery(sql);

// Process the results


while (rs.next()) {
System.out.println("Name: " + rs.getString("name") +
", Age: " + rs.getInt("age"));
}

// Close resources
rs.close();
st.close();
con.close();
} catch (Exception e) {

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

e.printStackTrace();
}
}
}

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 = con.prepareStatement(query);
// where pstmt is an object name
pstmt.setString(1,”Ayan”);
ptstmt.setInt(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 java.sql.*;

import java.util.Scanner;

class Geeks {

public static void main(String[] args) {

// try block to check for exceptions


try {

// Loading drivers using forName() method


Class.forName("com.mysql.cj.jdbc.Driver");

// Scanner class to take input from user


Scanner sc = new Scanner(System.in);

System.out.println(
"What age do you want to search?? ");

// Reading age an primitive datatype from user


// using nextInt() method
int age = sc.nextInt();

// Registering drivers using DriverManager


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

// Create a statement
PreparedStatement ps = con.prepareStatement(
"select name from world.people where age = ?");

// Execute the query


ps.setInt(1, age);
ResultSet res = ps.executeQuery();

// Condition check using next() method


// to check for element
while (res.next()) {

// Print and display elements(Names)


System.out.println("Name : "
+ res.getString(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


System.out.println(e);
}

// Catch block to handle class exceptions


catch (ClassNotFoundException e) {

// Print the line number where exception occurred


// using printStackTrace() method if any
e.printStackTrace();
}
}
}
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 = con.prepareCall(“{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 java.sql.*;

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


Class.forName("com.mysql.cj.jdbc.Driver");

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

// Create a CallableStatement
CallableStatement cs =
con.prepareCall("{call GetPeopleInfo()}");

// Execute the stored procedure


ResultSet res = cs.executeQuery();

// Process the results


while (res.next()) {

// Print and display elements (Name and Age)


System.out.println("Name : " + res.getString("name"));
System.out.println("Age : " + res.getInt("age"));
}

// Close resources
res.close();
cs.close();
con.close();
}
// Catch block for SQL exceptions
catch (SQLException e) {
e.printStackTrace();
}
// Catch block for ClassNotFoundException
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
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 = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table");

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

rs.close();
stmt.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace(); // Handle the exception
}

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 java.sql.Date

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 java.sql.Connection;
import java.sql.DriverManager
java.sql.DriverManager;
import java.sql.PreparedStat
java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class JDBCOperations {

// Establish database connection


private static Connection getConnection
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 DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);


}

// Insert record into the database


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

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

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


}

// Update record in the database


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

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

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

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


}

// Retrieve records from the database


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

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


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
19
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

double salary = resultSet.getDouble("salary");


System.out.println("ID: " + id + ", Name: " + name +
", Salary: " + salary);

}
}

// Delete record from the database


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

public static void main(String[] args) {


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

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

int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("Enter name:");

String nameToInsert = scanner.next();


System.out.println("Enter salary:");
double salaryToInsert = scanner.nextDouble();
insertRecord(connection, nameToInsert,
salaryToInsert);
break;

case 2:
System.out.println("Enter ID to update:");
int idToUpdate = scanner.nextInt();
System.out.println("Enter new name:");
String nameToUpdate = scanner.next();
System.out.println("Enter new salary:");
double salaryToUpdate
= scanner.nextDouble();
updateRecord(connection, idToUpdate,
20
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT

nameToUpdate, salaryToUpdate);
break;

case 3:
retrieveRecords(connection);
break;

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

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

// Close the connection at the end


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

Explanation of the above Program:


 Database Connection: Create Database connection by using configuration details like
username, password, database name and other information. Below we provide the
database connection java code.
 Insert Record: Now we implement logic for inserting new records by using this
connection object. And we use PreparedStatement for preventing SQL Injection and It
will takes input data in the form placeholders. After that we execute the SQL query by
using executeUpdate method from PreparedStatement.

 Update Record: Now we implement logic for update function. We employees details
based on their existing employee id only. It is same like inserting new record but before
that we fetch existing data then only we can able to update the data.

 Fetch All Records: Now we develop logic for fetching all records from the table by
using ResultSet object. First we execute the SQL query then hold that result in ResultSet
Object. Then we iterate that data and print line by line the entire data in the table.

 Delete Record by Using ID: In this function we can delete an existing employee record
by using employee ID from the Table.

 Main Function: In main function of the class, We develop logic for selecting operation
from the console by using switch statement in java. Based on the selection you can
perform related database operation. Below we provide that entire code for your reference.
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
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection( "jdbc:
"jdbc:mysql://localhost:3306/mydb
mysql://localhost:3306/mydb",
"username", "password");
System.out.println("Connection established.");
}
catch (Exception e) {
e.printStackTrace();
}

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 = con.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.setInt(3, 123);
statement.executeUpdate();
System.out.println("Record created.");
} catch (SQLException e) {
e.printStackTrace();
}

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 = con.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
String column1 = result.getString("column1");
String column2 = result.getString("column2");
int column3 = result.getInt("column3");
System.out.println("Column 1: " + column1);
System.out.println("Column 2: " + column2);
System.out.println("Column 3: " + column3);
}
} catch (SQLException e) {
e.printStackTrace();
}

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 = con.prepareStatement(sql);
statement.setString(1, "new_value1");
statement.setString(2, "new_value2");
statement.setInt(3, 456);
statement.setInt(4, 1);
statement.executeUpdate();
System.out.println("Record updated.");
} catch (SQLException e) {
e.printStackTrace();
}

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 = con.prepareStatement(sql);
statement.setInt(1, 1);
statement.executeUpdate();
System.out.println("Record deleted.");
} catch (SQLException e) {
e.printStackTrace();
}

25

You might also like