0% found this document useful (0 votes)
24 views17 pages

Understanding JDBC: Java Database Connectivity

JDBC (Java Database Connectivity) is a Java API that enables Java applications to connect to databases, execute SQL queries, and retrieve results. It acts as a bridge between Java applications and various databases through the use of database-specific drivers, allowing for CRUD operations. The process involves loading the JDBC driver, establishing a connection, creating statements, executing queries, and processing results using ResultSet.

Uploaded by

suryarough2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views17 pages

Understanding JDBC: Java Database Connectivity

JDBC (Java Database Connectivity) is a Java API that enables Java applications to connect to databases, execute SQL queries, and retrieve results. It acts as a bridge between Java applications and various databases through the use of database-specific drivers, allowing for CRUD operations. The process involves loading the JDBC driver, establishing a connection, creating statements, executing queries, and processing results using ResultSet.

Uploaded by

suryarough2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is JDBC?

JDBC stands for Java Database Connectivity.


It is a Java API (Application Programming Interface) that allows Java programs to connect to
databases, send SQL queries, and retrieve results from the database.

In simple terms, JDBC is a bridge between a Java application and a database like MySQL,
Oracle, or PostgreSQL.

What is JDBC API?

JDBC (Java Database Connectivity) is a Java API used to connect and execute queries with a
[Link] API is provided by Sun Microsystems (now Oracle).It provides a standard way
for Java applications to communicate with databases. JDBC API allows user to Perform CRUD
operations on databases (Create, Read, Update, Delete).

How JDBC Works

JDBC API provides a mechanism for dynamically loading the correct Java package and
registering it with the JDBC DriverManager. This mechanism helps to connect the Java
application to a particular database.

For example, if you're using Oracle DB:

JDBC API will identify the appropriate driver software and load it into memory to establish
the connection.

Java App

DataBase

JDBC
JDBC API cannot communicate with the database alone.

It requires the help of database-specific drivers. These drivers are provided by the respective
database vendors (e.g., MySQL, Oracle, PostgreSQL, etc.).The Java application communicates
with the JDBC API. JDBC API interacts with the database to perform the required operations.

How JDBC and Drivers Work Together

Driver
S/W

JAVA
APP
Driver
S/W

JDBC API
Driver
S/W

JDBC API acts as a bridge between the Java application and the [Link] communicate
with different types of databases: MySQL DB requires a MySQL driver, Oracle DB requires an
Oracle driver and PostgreSQL DB requires a PostgreSQL driver

Explanation with Example:

Let’s say we want to connect our Java application to an Oracle database: JDBC itself doesn't
know how to interact with Oracle DB directly. Oracle provides a JDBC driver. JDBC API loads
that driver and uses it to communicate with the Oracle DB.

5 Steps of JDBC (Java Database Connectivity)


1. Load or Registger the JDBC Driver

2. Establish the Connection

3. Create the Statement


4. Execute the Query

5. Close the Connection

Step 1: Load the JDBC Driver :


Before connecting to the database, you must load the JDBC driver for your database (like
MySQL, Oracle, etc.). This driver acts as a bridge between Java and the database.

[Link]("Fully_Qualified_DirverSoftware_name");

Eg- [Link]("[Link]");

OR

Step 1: Register the JDBC Driver :

JDBC driver acts as a bridge between Java application and the database. Before using it, we
need to register it with the DriverManager so that the application knows which driver to use
for connecting to the database.

Driver d = new Driver();

[Link](d);

Step 2: Establish the Connection


Now that the driver is loaded, now we have to connect your Java program to the actual
database. We can use getconnection method present inside DriverManager. There are three
get connection methods

1- getConnection(String)
2- getconnection(string, string ,string);
3- getConnection(String,properties);

Eg- Connection con =


[Link](
"jdbc:postgresql://localhost:5432/dbname", "user", "password");

Step 3: Create Statement


In JDBC, a Statement is an interface that is used to send SQL queries to the database from
your Java application. After establishing a connection, Java uses the Connection object to
create a [Link] Statement object sends SQL queries to the [Link] database
processes the query and sends results back to Java.

Eg- Statement stmt = [Link]();

What is a Statement
In JDBC, a Statement is an interface provided by the Java SQL package ([Link]).
It is used to execute SQL queries (like SELECT, INSERT, UPDATE, and DELETE) against a
relational database from a Java application.

Statement stmt = [Link]();

Here, con is a Connection object. Internally, createStatement() calls the implementation


provided by the JDBC driver . It returns an object that implements the Statement interface

A Statement is used to execute static SQL queries — where the entire SQL query is
hardcoded as a string.

Eg- Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM student");

it is used for Running simple, one-time SQL queries and Static queries that don’t change

What is PreparedStatement:
PreparedStatement is used to execute parameterized SQL queries. These queries are
precompiled by the database and can be executed multiple times with different inputs,
improving performance and preventing SQL injection.

SQL query is compiled once and stored Only parameter values change and we can execute
the same query for the multiple times.

Eg:

PreparedStatement pstmt =

[Link]("SELECT * FROM users WHERE id = ?");

[Link](1, 5);

ResultSet rs = [Link]();
You’re creating a PreparedStatement object using the Connection object.

You pass a parameterized SQL query:

"SELECT * FROM users WHERE id = ?"

Parameterized query (?):

? is a placeholder. It tells JDBC:

"I’ll provide the actual value for this parameter later."

A PreparedStatement object is created and ready to accept parameter [Link],

You're binding a value (5) to the 1st placeholder (?) in the SQL query. then,

1 → refers to the first parameter index (JDBC indexes start at 1).

5 → is the actual value you want to search for in the id column.

setInt() → is a type-specific setter method that safely sets the value as an integer.

Now the Query is ready to execute.

Execution Methods in JDBC :


In JDBC, you execute SQL commands using one of these three methods:

1- executeQuery()
2- executeUpdate()
3- execute()

1- execute()
this method is used to execute all kind of queries. the queries that return data and
for the queries that does not return data also. but executing the query that return data using
execute() method doesnt makes any sence . beacause this method return boolean data it
return you true if query return data eg . select queries and it return false if query does not
return data . but for the modification queries db will be affacted for like updte and delete
queries.

eg - statement = [Link]();

String sql = "SELECT * FROM users WHERE id = 1";


boolean isResultSet = [Link](sql);

2- executeUpdate()
Use case:

Used for data-modifying queries:

INSERT

UPDATE

DELETE

eg - PreparedStatement ps = [Link]("UPDATE users SET name = ?


WHERE id = ?");

[Link](1, "John");

[Link](2, 101);

int rowsAffected = [Link]();

It returns an integer indicating how many rows were affected by the query. 0 means no rows
were [Link] any integer number more than 0 that means n number of rows
[Link] will be sent to the DB. DB executes the modification. JDBC counts rows
affected and returns the count.

3- executeQuery()
it is used to execute the queries that return you data back afther the execution. Used only
for SELECT queries that return data. It returns a ResultSet object containing all rows and
columns from the SELECT query.

Eg- PreparedStatement ps =

[Link]("SELECT * FROM users WHERE id = ?");

[Link](1, 101);

ResultSet rs = [Link]();
The SQL SELECT query is sent to the DB. The DB executes it and returns the result set (table
format). JDBC wraps that result into a ResultSet object and return you back.

What is ResultSet in JDBC?


ResultSet is a table-like object in Java that holds the data returned by executing a

SELECT query on the database.

When you run a SELECT statement using executeQuery(), it returns a ResultSet object that

lets you access the rows and columns of the result.

How is ResultSet created?

Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM users");

How does the ResultSet Works:


Internally, the ResultSet behaves like a cursor (or pointer) that navigates through the rows
one by one. Before you call .next(), the cursor is positioned before the first row — think of it
like standing before the first record in table. Each time you call .next(), the cursor moves to
the next row and it return true of the row is present. When there are no more rows
left, .next() returns false.

Once the cursor is pointing to a valid row (after calling .next()), you can now read the data of
that row using getter methods:

.getString("columnindex") — gets a string value.

.getInt("columnindex") — gets an integer.

etc. as per the datatypes we have thhe methods.

eg -

ResultSet rs = [Link]("SELECT id, name FROM users");

while ([Link]()) {

sysout([Link](coloumnindex));

sysout([Link](coloumnindex));

...... }}
----------------------------

You have a POSTGRESQL table named employee:

CREATE TABLE employee (

id INT PRIMARY KEY,

name VARCHAR(100),

salary DOUBLE );

or create same kind of table from PGADMIN also fine.

Q - simple Java program using JDBC Statement that performs the following operations:

Inserts 3 employees

Updates 1 employee’s name

Deletes 1 employee

Ans :

public class EmployeeStatementExample {

public static void main(String[] args) {

String url = "";

String user = "";

String password = "";

try {

// 1. Load the driver (optional in modern JDBC, but safe to include)


[Link]("fully_Qualified_Name_of_DS");

// 2. Establish connection

Connection connection = [Link](url, user, password);

// 3. Create Statement object

Statement statement = [Link]();

// 4. Insert 3 employees

String insert1 = "INSERT INTO employee (id, name, salary) VALUES (1, 'Alice', 50000)";

String insert2 = "INSERT INTO employee (id, name, salary) VALUES (2, 'Bob', 60000)";

String insert3 = "INSERT INTO employee (id, name, salary) VALUES (3, 'Charlie',
55000)";

[Link](insert1);

[Link](insert2);

[Link](insert3);

[Link]("Inserted 3 employees.");

// 5. Update 1 employee (e.g., update name of id = 2)

String update = "UPDATE employee SET name = 'Bobby' WHERE id = 2";

[Link](update);

[Link]("Updated employee with id = 2.");

// 6. Delete 1 employee (e.g., delete employee with id = 1)

String delete = "DELETE FROM employee WHERE id = 1";

[Link](delete);

[Link]("Deleted employee with id = 1.");


} catch (Exception e) {

[Link]();

-------------------------------

Q- simple Java program using JDBC Statement and ResultSet to read and display all
employee records from the employee table.

Ans:

public class ReadEmployees {

public static void main(String[] args) {

String url = "";

String user = "";

String password = "";

try {

// 1. Load JDBC driver

[Link]("Fully_Qualified_Name_of_DS");

// 2. Create connection

Connection connection = [Link](url, user, password);


// 3. Create Statement

Statement statement = [Link]();

// 4. Execute SELECT query

String query = "SELECT * FROM employee";

ResultSet resultSet = [Link](query);

// 5. Process ResultSet

[Link]("Employee Details:");

[Link]("-----------------");

while ([Link]()) {

int id = [Link](1);

String name = [Link](2);

double salary = [Link](3);

[Link]("ID: " + id + ", Name: " + name + ", Salary: " + salary);

} catch (Exception e) {

[Link]();

----------------------------------------------------
Simple CRUD operations (Create, Read, Update, Delete) using PreparedStatement in Java
with JDBC.

public class EmployeePreparedStatementCRUD {

static final String URL = "";

static final String USER = "your_username";

static final String PASSWORD = "your_password";

public static void main(String[] args) {

try {

// 1. Load the Driver

[Link]("FullyQualifiedNameOfDriverSoftware");

// 2. Establish Connection

Connection connection = [Link](URL, USER, PASSWORD);

// 3. CREATE: Insert Employees

String insertQuery = "INSERT INTO employee (id, name, salary) VALUES (?, ?, ?)";

PreparedStatement insertStmt = [Link](insertQuery);

[Link](1, 1);

[Link](2, "Alice");

[Link](3, 50000.0);

[Link]();

[Link](1, 2);
[Link](2, "Bob");

[Link](3, 60000.0);

[Link]();

[Link](1, 3);

[Link](2, "Charlie");

[Link](3, 55000.0);

[Link]();

[Link]("Inserted 3 employees.");

// 4. READ: Fetch and display all employees

String selectQuery = "SELECT * FROM employee";

PreparedStatement selectStmt = [Link](selectQuery);

ResultSet rs = [Link]();

[Link]("All Employee Records:");

while ([Link]()) {

int id = [Link](1);

String name = [Link](2);

double salary = [Link](3);

[Link]("ID: " + id + ", Name: " + name + ", Salary: " + salary);

// 5. UPDATE: Update employee name for ID = 2

String updateQuery = "UPDATE employee SET name = ? WHERE id = ?";

PreparedStatement updateStmt = [Link](updateQuery);

[Link](1, "Bobby");
[Link](2, 2);

[Link]();

[Link]("\nUpdated name of employee with ID = 2");

// 6. DELETE: Delete employee with ID = 1

String deleteQuery = "DELETE FROM employee WHERE id = ?";

PreparedStatement deleteStmt = [Link](deleteQuery);

[Link](1, 1);

[Link]();

[Link]("Deleted employee with ID = 1");

} catch (Exception e) {

[Link]();

..............................................................

What is Batch Execution in JDBC?


Batch execution allows you to group multiple SQL statements together and execute them as
a batch, reducing the number of hits on the database. This is useful when you want to:
Insert many records at once.

Update many records at once.

Improve performance by avoiding repeated round trips to the DB.

PreparedStatement is precompiled once with placeholders ?.

For each record:


You set parameter values using setXXX().

Call addBatch() → Adds that set of values to the batch.

Once all records are added → call executeBatch().

JDBC sends all batched commands in one network call → improves performance.

DB executes each statement only onece on db.

eg :

public class BatchInsertExample {

public static void main(String[] args) {

String url = "";

String user = "your_username";

String password = "your_password";

try {

// 1. Load driver

[Link]("");

// 2. Establish connection

Connection connection = [Link](url, user, password);

// 3. Create PreparedStatement

String insertQuery = "INSERT INTO employee (id, name, salary) VALUES (?, ?, ?)";

PreparedStatement pstmt = [Link](insertQuery);

// 4. Set values for multiple employees

[Link](1, 101);
[Link](2, "Alice");

[Link](3, 50000.0);

[Link](); // Add to batch

[Link](1, 102);

[Link](2, "Bob");

[Link](3, 60000.0);

[Link](); // Add to batch

[Link](1, 103);

[Link](2, "Charlie");

[Link](3, 55000.0);

[Link](); // Add to batch

// 5. Execute all inserts at once

[Link]();

} catch (Exception e) {

[Link]();

Common questions

Powered by AI

To establish a JDBC connection from a Java application to a database, the key steps are: 1) Load or register the JDBC driver using Class.forName or DriverManager.registerDriver ; 2) Establish the connection with the database using DriverManager's getConnection method, which takes a URL, user, and password as parameters ; 3) Create a Statement or PreparedStatement object using the Connection object to send SQL queries to the database .

The JDBC API allows CRUD operations (Create, Read, Update, Delete) through its Statement and PreparedStatement interfaces. Creation operations use executeUpdate with SQL INSERT statements, reading is typically performed with executeQuery using SELECT statements, updating involves executeUpdate with SQL UPDATE statements, and deletions with executeUpdate using DELETE statements. Each operation involves setting up the Connection, creating a Statement or PreparedStatement, executing the command, and processing results if applicable .

A developer would prefer to use PreparedStatement over Statement when executing parameterized SQL queries or when the same query is run multiple times with different inputs. PreparedStatements are precompiled by the database, which improves performance by reducing parsing time for each execution, and they help prevent SQL injection attacks by separating the SQL logic from the data . Additionally, they provide type-safe setter methods to substitute parameter values, making the code cleaner and less error-prone .

In JDBC, the executeQuery method is used for executing SELECT queries that return data, returning a ResultSet containing the result . The executeUpdate method is used for data modification queries like INSERT, UPDATE, or DELETE, and it returns an integer representing the number of affected rows . The execute method can be used for any SQL command that may or may not return a result set, returning a boolean indicating whether a ResultSet was returned; however, it is less commonly used due to its ambiguity for data-modifying queries .

Batch execution in JDBC improves performance by reducing the number of round trips to the database. Instead of executing each SQL command separately, multiple commands are grouped into a batch and sent together in a single call. This reduces network overhead and allows the database to optimize execution. The steps involve creating a PreparedStatement, setting parameter values, calling addBatch for each set of values, and finally executing the entire batch with executeBatch .

Using the execute method in JDBC for SQL commands can be problematic because it returns a boolean, making it less intuitive for handling specific query results as it's unclear whether the command returns a result set or not without additional handling. This may lead to confusion, especially when distinguishing between SQL commands meant to modify data vs. those meant to query data, unlike executeQuery or executeUpdate, which provide more precise and meaningful returns based on query types .

PreparedStatements prevent SQL injection attacks by separating SQL logic from data inputs. SQL statements in PreparedStatement objects are precompiled, and inputs are treated as dynamic parameters using placeholders, thereby negating any ability to alter SQL commands through data manipulation. In contrast, Statements concatenate SQL queries with user inputs, which can be exploited to manipulate the queries maliciously if inputs are not sanitized properly .

Class.forName is traditionally used in JDBC to load and register a JDBC driver, thereby establishing database connectivity. It was a required step in older JDBC implementations to ensure the driver was loaded before establishing a connection. However, with modern JDBC versions, loading the driver automatically upon establishing a connection via DriverManager and a suitable JDBC URL reduces the need for explicitly calling Class.forName .

In JDBC, the ResultSet object holds the data returned by executing a SELECT query. It behaves like a cursor to navigate through the returned data rows one by one. When executing a query using executeQuery(), a ResultSet object is returned, which allows access to the data using getter methods like getString or getInt for column values. The cursor initially points before the first row and moves next with the next() method until no more rows are left .

The JDBC API acts as a standardized interface for Java applications to communicate with databases, allowing SQL queries to be executed and results to be retrieved. The API itself does not directly interact with the database; it relies on database-specific drivers to bridge the communication gap. These drivers, provided by database vendors like MySQL or Oracle, are registered with the DriverManager and loaded into memory to facilitate interaction with their respective databases .

You might also like