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

Jdbc Notes

JDBC (Java Database Connectivity) is an API that allows Java applications to interact with relational databases through a set of classes and interfaces. The typical JDBC workflow involves loading the driver, establishing a connection, executing SQL statements, and processing results while ensuring resources are closed properly. Key components include Statement, PreparedStatement, and CallableStatement, each serving different purposes in executing SQL and handling data securely and efficiently.

Uploaded by

thombreb956
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)
4 views

Jdbc Notes

JDBC (Java Database Connectivity) is an API that allows Java applications to interact with relational databases through a set of classes and interfaces. The typical JDBC workflow involves loading the driver, establishing a connection, executing SQL statements, and processing results while ensuring resources are closed properly. Key components include Statement, PreparedStatement, and CallableStatement, each serving different purposes in executing SQL and handling data securely and efficiently.

Uploaded by

thombreb956
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
You are on page 1/ 3

Comprehensive JDBC Notes

1. JDBC Overview
JDBC (Java Database Connectivity) is an API that enables Java applications to interact with relational databases.
It offers classes and interfaces to establish connections, execute SQL statements, and process results.
JDBC abstracts vendor■specific details, letting developers switch databases with minimal code change.

Important: Always close Connection, Statement, and ResultSet objects in a finally block or use
try–with■resources to avoid resource leaks.

2. Typical JDBC Workflow


1. Load the driver.
2. Establish a database connection via DriverManager or DataSource.
3. Create a Statement, PreparedStatement, or CallableStatement.
4. Execute SQL (executeQuery, executeUpdate, execute).
5. Process the ResultSet (if any).
6. Close resources.

3. Core JDBC Interfaces


Driver – Registers with DriverManager.
Connection – Logical connection to the database.
Statement – Executes static SQL.
PreparedStatement – Executes pre■compiled, parameterized SQL.
CallableStatement – Executes stored procedures.
ResultSet – Tabular data returned by queries.

4. Statement vs PreparedStatement vs CallableStatement


Statement
• Used for executing simple, static SQL.
• Susceptible to SQL injection.
• Compilation happens every execution.

PreparedStatement
• Pre■compiled SQL with placeholders (?).
• Prevents SQL injection and improves performance for repetitive queries.
• Supports batch execution.

CallableStatement
• Used to call stored procedures or functions in the database.
• Can handle IN, OUT, and INOUT parameters.
• Useful for encapsulating business logic within the DB.
5. execute(), executeQuery(), executeUpdate() –
Differences
executeQuery() – Runs SELECT statements. Returns a ResultSet. Use when you expect tabular data.
executeUpdate() – Runs INSERT, UPDATE, DELETE, CREATE, ALTER. Returns an int indicating affected rows
(or 0 for DDL).
execute() – General■purpose. Returns a boolean – true if the result is a ResultSet, else false. Must retrieve
results with getResultSet() or getUpdateCount().
Important: Prefer executeQuery() and executeUpdate() for clarity. Use execute() only when SQL can produce
either result type (e.g., stored procedures).

6. JDBC CRUD Example with PreparedStatement


import java.sql.*;
public class EmployeeDAO {
private static final String URL = "jdbc:mysql://localhost:3306/testdb";
private static final String USER = "root";
private static final String PASS = "password";

// CREATE
public void addEmployee(int id, String name, double salary) throws Exception {
String sql = "INSERT INTO employees(id, name, salary) VALUES (?, ?, ?)";
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, id);
ps.setString(2, name);
ps.setDouble(3, salary);
ps.executeUpdate();
}
}

// READ
public Employee getEmployee(int id) throws Exception {
String sql = "SELECT * FROM employees WHERE id = ?";
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return new Employee(rs.getInt("id"),
rs.getString("name"),
rs.getDouble("salary"));
}
}
return null;
}

// UPDATE
public void updateSalary(int id, double salary) throws Exception {
String sql = "UPDATE employees SET salary = ? WHERE id = ?";
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setDouble(1, salary);
ps.setInt(2, id);
ps.executeUpdate();
}
}

// DELETE
public void deleteEmployee(int id) throws Exception {
String sql = "DELETE FROM employees WHERE id = ?";
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, id);
ps.executeUpdate();
}
}
}

7. Interview Questions & Answers


What is JDBC?
JDBC is a Java API that enables Java programs to execute SQL statements and interact with relational databases
in a vendor■independent manner.
Explain the difference between Statement and PreparedStatement.
Statement compiles SQL each time and is vulnerable to SQL injection, while PreparedStatement is pre■compiled,
parameterized, and safer.
How does JDBC prevent SQL injection?
By using PreparedStatement placeholders, user inputs are treated as data, not executable SQL, eliminating
injection vectors.
What is batch processing and how is it achieved in JDBC?
Batch processing groups multiple SQL statements into a single batch using addBatch() and executeBatch(),
reducing network calls.
Describe the role of DriverManager.
DriverManager locates an appropriate JDBC driver and establishes a connection based on the specified URL.
What are scrollable and updatable ResultSets?
Scrollable ResultSets let you move forward and backward; updatable ResultSets allow row updates directly
through the ResultSet.
Why is connection pooling important?
Pooling reuses database connections, minimizing overhead and improving performance in high■traffic
applications.
Difference between execute(), executeQuery(), and executeUpdate().
executeQuery() returns ResultSet for SELECT, executeUpdate() returns row count for DML/DDL, execute()
handles both and returns a boolean.
How do you call a stored procedure from JDBC?
Use CallableStatement with syntax {call procedureName(?, ?)}, set parameters, and execute.
What is the advantage of using DataSource over DriverManager?
DataSource supports connection pooling, distributed transactions, and is configurable via JNDI, offering more
flexibility than DriverManager.

You might also like