Jdbc Notes
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.
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).
// 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();
}
}
}