JDBC (Java Database Connectivity) is the standard Java API used to connect Java applications with relational databases. It provides a common programming model for opening database connections, executing SQL statements, reading query results, managing transactions, and working with database metadata.
JDBC sits between the Java application and the database-specific JDBC driver.
Your Java code uses standard interfaces from java.sql, while the database driver handles the communication details required by a particular database such as MySQL, PostgreSQL, Oracle, or SQL Server.
JDBC in Simple Terms
Sends database requests using Java and JDBC APIs.
Provides the database-specific implementation needed for communication.
Executes SQL and returns data or an update result.
Why Is JDBC Important?
Most real-world applications need persistent data. An e-commerce application stores customers and orders, a learning platform stores users and course progress, and a banking application stores accounts and transactions. JDBC gives Java applications a standard way to communicate with relational database systems.
- Connect Java applications to relational databases.
- Execute SQL queries and commands.
- Read rows returned by SELECT statements.
- Insert, update, and delete database records.
- Control transactions with commit and rollback.
- Execute batches of SQL operations efficiently.
- Access stored procedures and database metadata.
Understanding the JDBC API
JDBC provides a collection of interfaces and classes primarily through packages such as
java.sql and javax.sql.
The most important objects developers encounter are Connection,
Statement, PreparedStatement, CallableStatement,
and ResultSet.
| JDBC Type | Purpose |
|---|---|
DriverManager |
Creates database connections using registered JDBC drivers. |
Connection |
Represents a connection to a database. |
Statement |
Executes SQL without parameter placeholders. |
PreparedStatement |
Executes parameterized SQL statements. |
CallableStatement |
Used to call stored procedures. |
ResultSet |
Represents rows returned by a query. |
JDBC Driver
A JDBC driver is the database-specific software that allows the Java application to communicate with a particular database. The JDBC API is standardized, but the driver knows how to translate JDBC operations into the protocol understood by the target database.
For example, a Java application connecting to MySQL requires a MySQL JDBC driver, while a PostgreSQL connection requires the PostgreSQL JDBC driver.
Modern JDBC drivers are normally discovered automatically when they are available on the application's classpath or module path.
Explicitly calling Class.forName() to load a JDBC driver is generally unnecessary with modern JDBC drivers, although you may still encounter that pattern in older code and tutorials.
JDBC Connection URL
A JDBC connection URL identifies the database and connection details required by the driver. The exact format depends on the database vendor.
String url =
"jdbc:mysql://localhost:3306/school";
String username = "root";
String password = "yourPassword";
In this example, jdbc:mysql: identifies the JDBC protocol and MySQL driver,
localhost is the database host,
3306 is the commonly used MySQL port,
and school is the database name.
Connecting to a Database
The DriverManager.getConnection() method can be used to obtain a JDBC Connection.
Connection connection =
DriverManager.getConnection(
url,
username,
password
);
System.out.println(
"Connected successfully."
);
The connection represents an active communication channel with the database. Applications should not keep a connection open indefinitely. It should be closed after the required database work is complete, or managed by a connection pool in larger applications.
The JDBC Workflow
A typical JDBC operation follows a predictable sequence:
Statement vs PreparedStatement
JDBC provides several ways to execute SQL.
Two of the most important are Statement and PreparedStatement.
Statement
Used when the SQL statement does not require dynamically supplied parameter values.
Statement statement =
connection.createStatement();
ResultSet rs =
statement.executeQuery(
"SELECT * FROM students"
);
PreparedStatement
Designed for parameterized SQL and is generally the preferred choice for dynamic values.
PreparedStatement ps =
connection.prepareStatement(
"SELECT * FROM students WHERE id = ?"
);
ps.setInt(1, 10);
ResultSet rs =
ps.executeQuery();
Why PreparedStatement Is Important
PreparedStatement allows SQL statements to contain placeholders such as ?.
Values are supplied separately using methods such as setString(), setInt(), setLong(), and setDouble().
This keeps SQL structure separate from supplied values and is a fundamental technique for reducing SQL injection risks.
String sql =
"SELECT id, name, email " +
"FROM students " +
"WHERE email = ?";
try (PreparedStatement statement =
connection.prepareStatement(sql)) {
statement.setString(
1,
"student@example.com"
);
try (ResultSet resultSet =
statement.executeQuery()) {
while (resultSet.next()) {
System.out.println(
resultSet.getString("name")
);
}
}
}
Executing SELECT Queries
SELECT statements return rows, so JDBC commonly executes them using executeQuery().
The returned ResultSet provides access to the rows returned by the database.
String sql =
"SELECT id, name, email FROM students";
try (PreparedStatement statement =
connection.prepareStatement(sql);
ResultSet resultSet =
statement.executeQuery()) {
while (resultSet.next()) {
int id =
resultSet.getInt("id");
String name =
resultSet.getString("name");
String email =
resultSet.getString("email");
System.out.println(
id + " - " + name + " - " + email
);
}
}
Understanding ResultSet
A ResultSet represents the data returned by a query.
Its cursor starts before the first row.
Calling next() moves the cursor to the next available row and returns true when a row exists.
Data can then be read using type-specific getter methods such as:
getInt()for integer valuesgetLong()for long integer valuesgetString()for text valuesgetDouble()for decimal valuesgetBoolean()for boolean valuesgetDate()and related APIs for date/time valuesgetObject()when a more generic representation is required
INSERT, UPDATE, and DELETE
SQL statements that modify data normally use executeUpdate().
The method returns the number of affected rows for many DML operations.
String sql =
"INSERT INTO students(name, email) " +
"VALUES (?, ?)";
try (PreparedStatement statement =
connection.prepareStatement(sql)) {
statement.setString(1, "Ananya");
statement.setString(
2,
"ananya@example.com"
);
int rows =
statement.executeUpdate();
System.out.println(
"Rows inserted: " + rows
);
}
The same pattern applies to UPDATE and DELETE statements.
Reading Generated Keys
When a database automatically generates identifiers, applications often need the generated key after an INSERT.
JDBC allows a statement to request generated keys and then read them from a ResultSet.
String sql =
"INSERT INTO students(name, email) " +
"VALUES (?, ?)";
try (PreparedStatement statement =
connection.prepareStatement(
sql,
Statement.RETURN_GENERATED_KEYS
)) {
statement.setString(1, "Rahul");
statement.setString(
2,
"rahul@example.com"
);
statement.executeUpdate();
try (ResultSet keys =
statement.getGeneratedKeys()) {
if (keys.next()) {
long id = keys.getLong(1);
System.out.println(
"Generated ID: " + id
);
}
}
}
JDBC Transactions
A transaction groups multiple database operations into a logical unit. This is essential when several changes must succeed together.
By default, a JDBC connection commonly uses auto-commit mode. When auto-commit is disabled, the application controls when changes are committed or rolled back.
connection.setAutoCommit(false);
try {
// Operation 1
updateAccountBalance();
// Operation 2
insertTransactionRecord();
connection.commit();
} catch (Exception e) {
connection.rollback();
throw e;
}
A transaction is especially important when several operations depend on one another. For example, transferring money between two accounts should not commit the debit while leaving the credit operation incomplete.
Batch Processing with JDBC
When many similar SQL statements need to be executed, repeatedly sending individual statements to the database can introduce unnecessary communication overhead.
JDBC supports batch execution through methods such as addBatch() and executeBatch().
String sql =
"INSERT INTO students(name, email) " +
"VALUES (?, ?)";
try (PreparedStatement statement =
connection.prepareStatement(sql)) {
for (int i = 1; i <= 3; i++) {
statement.setString(
1,
"Student " + i
);
statement.setString(
2,
"student" + i + "@example.com"
);
statement.addBatch();
}
int[] results =
statement.executeBatch();
System.out.println(
"Batch statements: "
+ results.length
);
}
JDBC Resource Management
JDBC resources such as Connection, Statement, and ResultSet should be closed when they are no longer required.
The recommended approach is try-with-resources.
try (
Connection connection =
DriverManager.getConnection(
url,
username,
password
);
PreparedStatement statement =
connection.prepareStatement(
"SELECT id, name FROM students"
);
ResultSet resultSet =
statement.executeQuery()
) {
while (resultSet.next()) {
System.out.println(
resultSet.getInt("id")
+ " - "
+ resultSet.getString("name")
);
}
} catch (SQLException e) {
e.printStackTrace();
}
Try-with-resources automatically closes resources at the end of the block, including when an exception occurs.
This is safer and cleaner than manually closing every JDBC object in a finally block.
SQLException
JDBC database operations commonly throw SQLException.
It contains information about database access failures and can expose details such as an error message, SQL state, vendor error code, and chained exceptions.
try {
// JDBC operation
} catch (SQLException e) {
System.err.println(
"Message: " + e.getMessage()
);
System.err.println(
"SQL state: " + e.getSQLState()
);
System.err.println(
"Error code: " + e.getErrorCode()
);
}
Connection Pooling
Opening a database connection can be relatively expensive compared with reusing an already established connection. For applications that serve many requests, creating a brand-new database connection for every operation can become inefficient.
Connection pooling keeps a managed collection of reusable database connections. A request borrows a connection from the pool, performs its database work, and returns the connection to the pool. Libraries such as HikariCP are commonly used for connection pooling in Java applications.
JDBC and SQL Injection
SQL injection occurs when untrusted input is inserted into an SQL command in a way that changes the intended query structure.
One of the fundamental defenses in JDBC is to use parameterized PreparedStatement queries rather than concatenating user input into SQL strings.
Unsafe Pattern
String sql =
"SELECT * FROM users " +
"WHERE name = '" + userInput + "'";
Preferred Pattern
String sql =
"SELECT * FROM users " +
"WHERE name = ?";
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userInput);
JDBC CRUD Example
The following example demonstrates the basic structure of a small JDBC data-access class.
The database schema is assumed to contain a students table with columns such as id, name, and email.
import java.sql.*;
public class StudentRepository {
private final String url =
"jdbc:mysql://localhost:3306/school";
private final String username = "root";
private final String password =
"yourPassword";
public void createStudent(
String name,
String email)
throws SQLException {
String sql =
"INSERT INTO students(name, email) " +
"VALUES (?, ?)";
try (
Connection connection =
DriverManager.getConnection(
url,
username,
password
);
PreparedStatement statement =
connection.prepareStatement(sql)
) {
statement.setString(1, name);
statement.setString(2, email);
statement.executeUpdate();
}
}
public void findStudents()
throws SQLException {
String sql =
"SELECT id, name, email " +
"FROM students " +
"ORDER BY id";
try (
Connection connection =
DriverManager.getConnection(
url,
username,
password
);
PreparedStatement statement =
connection.prepareStatement(sql);
ResultSet resultSet =
statement.executeQuery()
) {
while (resultSet.next()) {
System.out.println(
resultSet.getLong("id")
+ " - "
+ resultSet.getString("name")
+ " - "
+ resultSet.getString("email")
);
}
}
}
public void deleteStudent(long id)
throws SQLException {
String sql =
"DELETE FROM students WHERE id = ?";
try (
Connection connection =
DriverManager.getConnection(
url,
username,
password
);
PreparedStatement statement =
connection.prepareStatement(sql)
) {
statement.setLong(1, id);
statement.executeUpdate();
}
}
}
JDBC Result Handling
JDBC gives you low-level control over the database interaction.
That flexibility also means your application often needs to convert rows from the ResultSet into Java objects.
public record Student(
long id,
String name,
String email
) {
}
Student student = new Student(
resultSet.getLong("id"),
resultSet.getString("name"),
resultSet.getString("email")
);
In larger applications, this mapping responsibility is commonly isolated inside repository or data-access classes. Frameworks such as Hibernate provide higher-level object-relational mapping on top of concepts that JDBC exposes more directly.
JDBC vs Hibernate
JDBC and Hibernate are not competing database technologies in the same sense. JDBC is the standard low-level Java database connectivity API, while Hibernate is a higher-level ORM framework that can use JDBC internally to communicate with relational databases.
| JDBC | Hibernate |
|---|---|
| Lower-level database API | Higher-level ORM framework |
| Developer writes SQL directly | Can generate SQL from entity operations and queries |
| Manual row-to-object mapping | Entity mapping handled by ORM |
| Fine-grained control over SQL | Higher productivity for object-oriented persistence |
When Should You Use JDBC?
JDBC can be a good choice when you need direct control over SQL and database operations. It is particularly useful for learning database fundamentals, writing focused data-access code, working with complex SQL, or building applications where ORM abstraction would not provide enough value.
In larger applications, JDBC is frequently used indirectly through frameworks, libraries, repositories, database utilities, and ORM implementations. Understanding JDBC therefore remains valuable even when you eventually work with Hibernate or another persistence framework.
Common JDBC Mistakes
Hardcoding Database Credentials
Database usernames, passwords, and production connection details should not be permanently embedded in source code. Use appropriate application configuration and secret management.
Building SQL with String Concatenation
Avoid placing user-controlled values directly into SQL strings.
Use parameterized PreparedStatement queries.
Not Closing Resources
Unclosed connections and statements can exhaust database or application resources. Prefer try-with-resources.
Ignoring Transactions
Related database operations can leave data inconsistent when each operation is committed independently. Define appropriate transaction boundaries.
Opening Too Many Connections
Creating a new database connection for every request can become expensive. Production applications commonly use connection pooling.
Using SELECT *
Selecting every column when only a few are required can increase data transfer and make queries less explicit. Select the columns needed by the use case.
JDBC Best Practices
- Use
PreparedStatementfor parameterized SQL. - Use try-with-resources to close JDBC resources safely.
- Keep database credentials outside source code and manage them through secure configuration.
- Use transactions when multiple operations must succeed or fail together.
- Use connection pooling for applications with frequent database access.
- Select only the columns required by the operation.
- Use batch execution when many similar operations need to be sent to the database.
- Keep SQL and data-access responsibilities separate from business logic where appropriate.
- Understand database indexes, constraints, joins, and query plans instead of relying only on Java-side optimization.
A Practical JDBC Mental Model
A useful way to remember JDBC is to think in terms of responsibilities:
How Java reaches the database.
How Java sends parameterized SQL.
How Java reads returned rows.
How Java controls commit and rollback.
Key Takeaways
JDBC is the standard Java API for connecting applications to relational databases.
The main JDBC building blocks are Connection, Statement,
PreparedStatement, CallableStatement, and ResultSet.
PreparedStatement is the preferred approach for SQL containing external or dynamic values.
ResultSet provides access to rows returned by SELECT queries.
Transactions allow multiple related operations to be committed or rolled back as one unit.
Try-with-resources helps safely release JDBC resources.
JDBC is lower-level than ORM frameworks such as Hibernate, but understanding it gives you a strong foundation for database programming and helps you understand what higher-level persistence frameworks are doing underneath.