Chapter 14
Java JDBC
4 topics · 1 sections · beginner-friendly study notes · Updated
JDBC (Java Database Connectivity) is the standard Java API in java.
sql for talking to relational databases.
This chapter explains what JDBC is, the four driver types, the steps to connect and run SQL, and why PreparedStatement is better than Statement.
Almost every enterprise application stores data in a relational database, and frameworks such as Hibernate and Spring are built on top of JDBC.
Student management systems, banking apps, login modules, reports and any backend that reads or writes SQL data.
Introduction to JDBC
JDBC (Java Database Connectivity) is a Java API in the java.sql and javax.sql packages that lets a Java program connect to a relational database, send SQL statements and process the results in a database-independent way.
In short: JDBC is the translator between your Java code and any SQL database such as MySQL, Oracle or PostgreSQL.
Think about it
Switching from MySQL to Oracle should need little more than a different driver and URL; JDBC provides this uniform interface. A universal remote: the same buttons (API) work with different TVs (databases) once you plug in the right adapter (driver).
Architecture: Java application → JDBC API → DriverManager (or DataSource) → vendor JDBC driver → database.
Key types: DriverManager (finds the driver and creates connections), Connection (a session; also controls transactions via setAutoCommit, commit, rollback), `Statement, PreparedStatement and CallableStatement (stored procedures) to run SQL, ResultSet (cursor over query rows, positioned before the first row; next() moves forward), ResultSetMetaData, DatabaseMetaData and SQLException`.
executeQuery is for SELECT and returns a ResultSet, executeUpdate is for INSERT/UPDATE/DELETE/DDL and returns the number of affected rows, and execute returns a boolean for either.
Since JDBC 4.0 drivers on the classpath are auto-discovered through the ServiceLoader, so Class.
forName is rarely needed.
In production, connections come from a connection pool (HikariCP) through javax.
sql.
DataSource because opening connections is expensive.
JDBC is low-level: you handle SQL, mapping and resources manually, which ORM tools automate.
Key points
- DriverManager: Class that manages drivers and returns Connection objects.
- Connection: Session with the database.
- ResultSet: Table of results from a query, read row by row.
- DataSource: Factory for connections, usually backed by a pool.
- SQLException: Checked exception for database errors.
- Packages: java.sql (core) and javax.sql (DataSource, pooling).
- executeQuery
→ResultSet; executeUpdate→int rows affected; execute→boolean. - ResultSet columns are 1-indexed;
next()returns false after the last row. - Use connection pools in real applications.
Example
CodeCore JDBC types and what each returns:
import java.sql.*;
import java.util.Collections;
public class JdbcIntro {
public static void main(String[] args) {
// List the drivers currently registered with DriverManager
for (Driver d : Collections.list(DriverManager.getDrivers())) {
System.out.println("Driver: " + d.getClass().getName());
}
System.out.println("Login timeout: " + DriverManager.getLoginTimeout()); // 0
// Typical use (needs a running database and the driver jar on the classpath):
// Connection con = DriverManager.getConnection(url, user, pass);
// Statement st = con.createStatement();
// ResultSet rs = st.executeQuery("SELECT id, name FROM students");
// while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); }
// int rows = st.executeUpdate("UPDATE students SET name='X' WHERE id=1"); // rows affected
// con.close();
}
}JDBC Driver Types
A JDBC driver is a vendor-supplied library that implements the JDBC interfaces and translates JDBC calls into database-specific calls. There are four types: Type 1 (JDBC-ODBC bridge), Type 2 (native-API / partly Java), Type 3 (network protocol / middleware) and Type 4 (thin, pure Java driver).
In short: Drivers are different kinds of adapters; Type 4 is a plain Java plug that talks directly to the database and is the one everyone uses now.
Think about it
Choosing the right driver affects portability, performance and deployment; the types are a standard theory question. Type 1: using a translator who translates through a second translator; Type 4: talking directly in the other person language.
Type 1 uses the ODBC driver of the operating system through a bridge: slow, needs ODBC installed, platform dependent and was REMOVED in Java 8.
Type 2 converts JDBC calls into the database client library calls (for example Oracle OCI): faster than Type 1 but needs native client code on each machine, so it is not portable.
Type 3 sends JDBC calls over the network to a middleware server which translates them to the database protocol: flexible for many databases, but needs an extra server tier.
Type 4 (thin driver) is written entirely in Java and speaks the database network protocol directly: platform independent, easy to deploy (just a jar on the classpath), and the best performance in most cases; examples: MySQL Connector/J (com.
mysql.
cj.
jdbc.
Driver), PostgreSQL (org.
postgresql.
Driver), Oracle thin (oracle.
jdbc.
OracleDriver), SQL Server (com.
microsoft.
sqlserver.
jdbc.
SQLServerDriver).
The JDBC URL tells DriverManager which driver to use: jdbc:<subprotocol>://host:port/database.
Key points
- Type 1: JDBC-ODBC bridge (removed in Java 8).
- Type 2: Native-API driver, needs client libraries.
- Type 3: Network-protocol driver using middleware.
- Type 4: Thin pure-Java driver, direct to database.
- JDBC URL: Connection string such as jdbc:mysql://localhost:3306/school.
Read more
Example
CodeJDBC URLs, driver loading and lookup:
import java.sql.*;
public class DriverTypesDemo {
public static void main(String[] args) {
// Type 4 JDBC URLs (the driver jar must be on the classpath)
String mysql = "jdbc:mysql://localhost:3306/school";
String postgres = "jdbc:postgresql://localhost:5432/school";
String oracle = "jdbc:oracle:thin:@localhost:1521:XE"; // 'thin' = Type 4
String sqlite = "jdbc:sqlite:school.db";
System.out.println(mysql.split(":")[1]); // mysql
System.out.println(oracle.contains("thin")); // true
// Pre-JDBC 4 style: load the driver class by name
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Driver jar missing from classpath");
}
// DriverManager chooses a driver by URL
try {
Driver d = DriverManager.getDriver(sqlite);
System.out.println("Using " + d.getClass().getName());
} catch (SQLException e) {
System.out.println(e.getMessage()); // No suitable driver (when no jar is present)
}
}
}Type 1: JDBC-ODBC bridge
Bridge to ODBC; slow, platform-dependent, no longer available.
Type 2: Native API
Calls the vendor client library; faster, but not portable.
Type 3: Network protocol
Talks to a middleware server that talks to the database.
Type 4: Thin driver
Pure Java, direct protocol; most used and recommended.
JDBC Connectivity Steps
The JDBC connectivity steps are the standard sequence for using a database from Java: (1) register/load the driver, (2) create a Connection, (3) create a Statement, (4) execute the SQL, (5) process the ResultSet, (6) close the resources.
In short: Plug in the driver, open the connection, send your SQL, read the answer, and close everything.
Think about it
Every JDBC program follows these steps; viva and lab exams ask you to write them in order. Phoning a shop: dial (connection), ask for an item (statement), listen to the answer (result set) and hang up (close).
Step 1: with JDBC 4+ simply put the driver jar on the classpath; older code used `Class.
forName("driver.
ClassName")`.
Step 2: `DriverManager.
getConnection(url, user, password)` returns a Connection or throws SQLException (wrong URL, credentials, server down).
Step 3: `con.
createStatement() or con.
prepareStatement(sql)`.
Step 4: executeQuery for SELECT, executeUpdate for DML/DDL.
Step 5: loop with `while (rs.
next()) and read columns with getInt, getString, getDouble, getDate` by name or 1-based index.
Step 6: close ResultSet, Statement and Connection in reverse order of creation — best with try-with-resources so they close even on exceptions; failing to close leaks connections.
Transactions: `con.
setAutoCommit(false), then commit() on success and rollback()` in the catch block.
Never hard-code passwords in source; read them from environment variables or configuration.
Handle SQLException with getMessage(), getSQLState() and getErrorCode().
Key points
- getConnection: DriverManager method that opens a database session.
- AutoCommit: Every statement is committed immediately when true (default).
- Transaction: Group of statements that succeed or fail together.
- getSQLState: Standard 5-character code describing the error.
- Order: driver
→connection→statement→execute→process→close. - Column index in ResultSet starts at 1.
- Close in reverse order; prefer try-with-resources.
- For transactions:
setAutoCommit(false),commit(),rollback().
Read more
Example
CodeComplete JDBC program using all six steps:
import java.sql.*;
public class StudentJdbc {
static final String URL = "jdbc:mysql://localhost:3306/school";
static final String USER = System.getenv("DB_USER");
static final String PASS = System.getenv("DB_PASS");
public static void main(String[] args) {
// Steps 1 & 2: driver on classpath (JDBC 4), open connection
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
Statement st = con.createStatement()) { // Step 3
st.executeUpdate("CREATE TABLE IF NOT EXISTS students(" +
"id INT PRIMARY KEY, name VARCHAR(50), marks INT)");
int rows = st.executeUpdate("INSERT INTO students VALUES (1, 'Amit', 90)"); // Step 4
System.out.println(rows + " row inserted");
try (ResultSet rs = st.executeQuery("SELECT id, name, marks FROM students")) {
while (rs.next()) { // Step 5
System.out.println(rs.getInt("id") + " " + rs.getString(2) + " " + rs.getInt(3));
}
}
// Transaction example
con.setAutoCommit(false);
try {
st.executeUpdate("UPDATE students SET marks = marks - 10 WHERE id = 1");
st.executeUpdate("UPDATE students SET marks = marks + 10 WHERE id = 2");
con.commit();
} catch (SQLException e) {
con.rollback(); // undo both updates
System.out.println("Rolled back: " + e.getMessage());
}
} catch (SQLException e) { // Step 6: resources auto-closed
System.out.println("DB error: " + e.getMessage() + " [" + e.getSQLState() + "]");
}
}
}Statement vs PreparedStatement
Statement executes a plain SQL string that is compiled by the database every time. PreparedStatement is a subinterface of Statement that takes a precompiled SQL template with ? placeholders and binds the values with setXxx() methods before executing.
In short: Statement glues the values into the SQL text; PreparedStatement keeps the SQL fixed and passes the values separately, which is faster and safe.
Think about it
SQL injection is one of the most common security flaws, and this comparison is a certain interview question. Statement: dictating the whole order including your own words to the chef who may misinterpret them. PreparedStatement: filling in a printed order form with blank fields.
With Statement you build "SELECT * FROM users WHERE name='" + name + "'"; if name is x' OR '1'='1 the query changes meaning (SQL injection).
PreparedStatement sends the SQL structure once and the parameters as data, so they can never be interpreted as SQL.
Parameters are set with setInt(1, id), setString(2, name), setDate, setNull; the index starts at 1.
The database can cache the execution plan and reuse it, giving better performance for repeated queries.
Batch processing: addBatch() repeatedly then executeBatch() inserts many rows efficiently.
PreparedStatement also handles quoting, dates and special characters correctly.
Placeholders can replace values only, NOT table or column names.
CallableStatement (extends PreparedStatement) calls stored procedures with `{call proc(?
, ?
)}`.
Use Statement only for static SQL with no user input (for example DDL); use PreparedStatement for everything else.
Key points
- Placeholder (?): Parameter marker in a prepared SQL string.
- Precompiled: SQL parsed and planned once, run many times.
- SQL injection: Attack that changes a query by inserting SQL text through input.
- Batch: Several statements sent to the database in one round trip.
- CallableStatement: Interface for calling stored procedures.
- Statement: dynamic SQL, no parameters, injection-prone, compiled each time.
- PreparedStatement: ? placeholders, precompiled, injection-safe, faster for repeated use.
- Parameter index starts at 1.
- Placeholders cannot be used for table or column names.
Read more
Example
CodeSQL injection with Statement vs safe PreparedStatement:
import java.sql.*;
public class PreparedDemo {
static void login(Connection con, String user, String pass) throws SQLException {
// UNSAFE: Statement with string concatenation
String bad = "SELECT * FROM users WHERE name='" + user + "' AND pass='" + pass + "'";
System.out.println(bad);
// For user = x' OR '1'='1 the query becomes:
// SELECT * FROM users WHERE name='x' OR '1'='1' AND pass='' -> returns rows!
// SAFE: PreparedStatement
String sql = "SELECT id FROM users WHERE name = ? AND pass = ?";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, user); // bound as data, never as SQL
ps.setString(2, pass);
try (ResultSet rs = ps.executeQuery()) {
System.out.println(rs.next() ? "Login OK" : "Login failed");
}
}
}
static void bulkInsert(Connection con) throws SQLException {
String sql = "INSERT INTO students(id, name, marks) VALUES (?, ?, ?)";
try (PreparedStatement ps = con.prepareStatement(sql)) {
String[] names = {"Amit", "Neha", "Ravi"};
for (int i = 0; i < names.length; i++) {
ps.setInt(1, i + 1);
ps.setString(2, names[i]);
ps.setInt(3, 80 + i);
ps.addBatch(); // queue
}
int[] counts = ps.executeBatch(); // one round trip
System.out.println(counts.length + " rows inserted"); // 3 rows inserted
}
}
public static void main(String[] args) throws SQLException {
// needs a real connection: DriverManager.getConnection(url, user, password)
// login(con, "x' OR '1'='1", ""); // safe version returns "Login failed"
System.out.println("See login() and bulkInsert()");
}
}Solved examples
List the JDBC steps in the correct order.
Ordered steps
Formula Applied:—Approach note: Write "DCS-EPC" as a memory aid.
Which method do you call for SELECT and which for INSERT/UPDATE/DELETE?
Method names with return types
Formula Applied:—Approach note: execute() works for both and returns a boolean.
Rewrite "SELECT * FROM student WHERE roll = " + roll safely.
PreparedStatement code
Formula Applied:—Approach note: JDBC parameter indexes start at 1, not 0.
Why prefer PreparedStatement with ? placeholders over Statement with string concatenation for: SELECT * FROM users WHERE id = userInput?
Security + plan reuse
Formula Applied:—Approach note: Rule: user data → setInt/setString on PreparedStatement only.
Real-world applications
Using Java JDBC in real projects
Student management systems, banking apps, login modules, reports and any backend that reads or writes SQL data.
Common mistakes
❌ Myth: Type 1 driver is the most commonly used.
Why this is wrong: It needs ODBC and was removed in Java 8.
✅ Verified Truth: Type 4 (thin) driver is the standard choice.
⚠️ Exam Tip: Remember: Type 4 = pure Java, direct to database.
❌ Myth: PreparedStatement is only about speed.
Why this is wrong: Its main benefit is security against SQL injection.
✅ Verified Truth: Bound parameters can never change the SQL structure.
⚠️ Exam Tip: Always mention both security and performance.
❌ Myth: ResultSet column indexes start at 0.
Why this is wrong: JDBC uses 1-based indexes.
✅ Verified Truth: First column is getString(1).
⚠️ Exam Tip: Same rule for PreparedStatement parameters.
❌ Myth: Closing the Connection is optional.
Why this is wrong: Unclosed connections leak resources and exhaust the database.
✅ Verified Truth: Use try-with-resources or finally to close.
⚠️ Exam Tip: With a pool, close() returns the connection to the pool.
Revision notes
JDBC (Java Database Connectivity) is the standard Java API in java.sql for talking to relational databases. This chapter explains what JDBC is, the four driver types, the steps to connect and run SQL, and why PreparedStatement is better than Statement.
High-Yield Quick Revision Points
- JDBC = java.sql API; DriverManager → Connection → Statement → ResultSet
- Types: 1 ODBC bridge (removed), 2 native, 3 middleware, 4 thin pure Java
- Steps: driver, connection, statement, execute, process, close
- executeQuery → ResultSet; executeUpdate → int; indexes start at 1
- PreparedStatement: precompiled, ? params, injection-safe, batching
- Use try-with-resources; transactions via setAutoCommit(false)/commit/rollback
Practice questions
Which package contains the core JDBC API?
Which driver type is a pure Java thin driver?
Which method returns a ResultSet?
PreparedStatement uses which symbol for parameters?
Which statement prevents SQL injection?
What does executeUpdate() return?