Java Database Connectivity (JDBC) is an API that allows Java applications to interact with databases. JDBC provides a standard interface for connecting to relational databases, executing SQL queries, and retrieving results.
JDBC is part of the Java Standard Edition (Java SE) and provides methods for querying and updating data in a database. The key features of JDBC include:
The JDBC architecture consists of two main layers:
There are four types of JDBC drivers:
To use JDBC, you need to include the database-specific JDBC driver in your project. For example, for MySQL, you can download the MySQL Connector/J driver from the MySQL website and include it in your classpath.
Ensure you have a running database server. For this guide, we’ll use a MySQL database. Create a database and a sample table:
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
You can use any IDE like IntelliJ IDEA, Eclipse, or even a simple text editor. Ensure that your Java Development Kit (JDK) is installed and configured.
The first step in any JDBC program is to establish a connection to the database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root"; // replace with your database user
String password = "password"; // replace with your database password
try (Connection connection = DriverManager.getConnection(url, user, password)) {
if (connection != null) {
System.out.println("Connected to the database!");
}
} catch (SQLException e) {
System.err.println("Connection failed: " + e.getMessage());
}
}
}
Once connected, you can execute SQL statements using the Statement
, PreparedStatement
, or CallableStatement
interfaces.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement()) {
// Create table if it doesn't exist
String createTableSQL = "CREATE TABLE IF NOT EXISTS users (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(100), " +
"email VARCHAR(100))";
statement.executeUpdate(createTableSQL);
// Insert data
String insertSQL = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
statement.executeUpdate(insertSQL);
System.out.println("Data inserted successfully!");
} catch (SQLException e) {
System.err.println("SQL error: " + e.getMessage());
}
}
}
To retrieve data from the database, you use the ResultSet
object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrieveExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement()) {
String querySQL = "SELECT * FROM users";
ResultSet resultSet = statement.executeQuery(querySQL);
// Iterate through the ResultSet
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
} catch (SQLException e) {
System.err.println("SQL error: " + e.getMessage());
}
}
}
Using PreparedStatement
is recommended for executing queries, especially when dealing with user input. It helps prevent SQL injection attacks and improves performance.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PreparedStatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {
preparedStatement.setString(1, "Alice Smith");
preparedStatement.setString(2, "alice@example.com");
preparedStatement.executeUpdate();
System.out.println("Data inserted successfully!");
} catch (SQLException e) {
System.err.println("SQL error: " + e.getMessage());
}
}
}
You can also update and delete records using PreparedStatement
.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateDeleteExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
// Update example
String updateSQL = "UPDATE users SET email = ? WHERE name = ?";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement updateStatement = connection.prepareStatement(updateSQL)) {
updateStatement.setString(1, "alice.new@example.com");
updateStatement.setString(2, "Alice Smith");
int rowsUpdated = updateStatement.executeUpdate();
System.out.println(rowsUpdated + " rows updated!");
} catch (SQLException e) {
System.err.println("SQL error: " + e.getMessage());
}
// Delete example
String deleteSQL = "DELETE FROM users WHERE name = ?";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement deleteStatement = connection.prepareStatement(deleteSQL)) {
deleteStatement.setString(1, "Alice Smith");
int rowsDeleted = deleteStatement.executeUpdate();
System.out.println(rowsDeleted + " rows deleted!");
} catch (SQLException e) {
System.err.println("SQL error: " + e.getMessage());
}
}
}
Proper error handling is crucial in JDBC applications. Common exceptions include:
SQLException
: Indicates a database access error or other errors.ClassNotFoundException
: Thrown when the JDBC driver class is not found.
try {
// Database operations...
} catch (SQLException e) {
System.err.println("SQL error: " + e.getErrorCode() + " - " + e.getMessage());
} catch (ClassNotFoundException e) {
System.err.println("JDBC Driver not found: " + e.getMessage());
}
Connection pooling is a technique to manage database connections efficiently. It improves performance by reusing existing connections rather than creating new ones for each request.
Add the HikariCP dependency to your project:
com.zaxxer
HikariCP
5.0.1
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionPoolExample {
private static HikariDataSource dataSource;
static {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/testdb");
config.setUsername("root");
config.setPassword("password");
config.setMaximumPoolSize(10);
dataSource = new HikariDataSource(config);
}
public static void main(String[] args) {
try (Connection connection = dataSource.getConnection()) {
System.out.println("Connected to the database using connection pool!");
} catch (SQLException e) {
System.err.println("Connection pool error: " + e.getMessage());
}
}
}