JDBC stands for Java Database Connectivity. It is a Java API used to connect Java applications to databases such as MySQL, PostgreSQL, and Oracle.
Using JDBC, we can:
JDBC provides interfaces and classes that allow Java programs to communicate with databases.
| Component | Purpose |
|---|---|
DriverManager |
Obtains database connections. |
Connection |
Represents a connection to a database. |
Statement |
Executes SQL statements. |
PreparedStatement |
Executes parameterized SQL statements. |
ResultSet |
Represents the results of a query. |
A basic JDBC application works in this order:
Java Application
|
v
JDBC API
|
v
JDBC Driver
|
v
Database
Before connecting Java to MySQL, you need:
For a Maven project, add the MySQL Connector/J dependency
to your pom.xml. Use a current compatible
version from the official MySQL documentation.
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>YOUR_COMPATIBLE_VERSION</version>
</dependency>
YOUR_COMPATIBLE_VERSION with a real
Connector/J version. The dependency must be downloaded
and available to your project.
First, create a database and a table in MySQL.
CREATE DATABASE schooldb;
USE schooldb;
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age INT,
course VARCHAR(100)
);
The students table stores a student's ID,
name, age, and course.
Use DriverManager.getConnection() to
establish a connection to MySQL.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "YOUR_PASSWORD";
try (Connection con =
DriverManager.getConnection(
url, username, password)) {
System.out.println("Database connected successfully");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Database connected successfully
YOUR_PASSWORD with your local
MySQL password. Do not commit real database passwords
to public source-code repositories.
Modern JDBC drivers are normally discovered automatically
when the driver JAR is available. Explicitly calling
Class.forName() is usually unnecessary.
A PreparedStatement executes parameterized
SQL. The question marks are replaced with values using
setter methods.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "YOUR_PASSWORD";
String sql =
"INSERT INTO students (name, age, course) " +
"VALUES (?, ?, ?)";
try (Connection con =
DriverManager.getConnection(
url, username, password);
PreparedStatement ps =
con.prepareStatement(sql)) {
ps.setString(1, "Rahul");
ps.setInt(2, 20);
ps.setString(3, "Java");
int rows = ps.executeUpdate();
System.out.println(
rows + " record inserted successfully"
);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
1 record inserted successfully
executeUpdate() returns the number of
affected rows for an insert, update, or delete operation.
Use executeQuery() to execute a SELECT
statement. The returned ResultSet lets
you read each row.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "YOUR_PASSWORD";
String sql = "SELECT id, name, age, course FROM students";
try (Connection con =
DriverManager.getConnection(
url, username, password);
PreparedStatement ps =
con.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
System.out.println("Age: " + rs.getInt("age"));
System.out.println("Course: " + rs.getString("course"));
System.out.println("----------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ID: 1
Name: Rahul
Age: 20
Course: Java
----------------
The output depends on the records currently stored in the database.
Use an UPDATE statement with
PreparedStatement to change existing records.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "YOUR_PASSWORD";
String sql =
"UPDATE students SET course = ? WHERE id = ?";
try (Connection con =
DriverManager.getConnection(
url, username, password);
PreparedStatement ps =
con.prepareStatement(sql)) {
ps.setString(1, "Python");
ps.setInt(2, 1);
int rows = ps.executeUpdate();
System.out.println(
rows + " record(s) updated"
);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
1 record(s) updated
This updates the course for the student whose ID is 1. The number of affected rows depends on the database data and whether the update changes any values.
Use a DELETE statement to remove a record. Always use a suitable WHERE condition to avoid deleting unintended records.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "YOUR_PASSWORD";
String sql = "DELETE FROM students WHERE id = ?";
try (Connection con =
DriverManager.getConnection(
url, username, password);
PreparedStatement ps =
con.prepareStatement(sql)) {
ps.setInt(1, 1);
int rows = ps.executeUpdate();
System.out.println(
rows + " record(s) deleted"
);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
1 record(s) deleted
Use a parameterized WHERE condition to retrieve specific records.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "YOUR_PASSWORD";
String sql =
"SELECT id, name, course FROM students WHERE age > ?";
try (Connection con =
DriverManager.getConnection(
url, username, password);
PreparedStatement ps =
con.prepareStatement(sql)) {
ps.setInt(1, 18);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(
rs.getInt("id") + " - " +
rs.getString("name") + " - " +
rs.getString("course")
);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This query returns students older than 18. The results depend on the database records.
| Statement | PreparedStatement |
|---|---|
| Executes SQL statements. | Executes parameterized SQL statements. |
| Values may need manual string construction. | Values can be supplied using setter methods. |
| String concatenation can create SQL injection risks. | Helps prevent SQL injection for bound parameter values. |
| Suitable for simple fixed SQL. | Usually preferred for queries with input values. |
PreparedStatement for user-supplied values.
Do not build SQL queries by concatenating untrusted input.
| Method | Purpose |
|---|---|
getConnection() |
Opens a database connection. |
prepareStatement() |
Creates a PreparedStatement. |
executeQuery() |
Executes a SELECT query and returns a ResultSet. |
executeUpdate() |
Executes an INSERT, UPDATE, DELETE, or suitable SQL statement that does not return a ResultSet. |
execute() |
Executes SQL when the result type may vary. |
next() |
Moves the ResultSet cursor to the next row. |
getString() |
Reads a column as a String. |
getInt() |
Reads a column as an int. |
close() |
Closes a JDBC resource. |
Try-with-resources, used in the examples above, automatically closes connections, statements, and result sets when they leave the try block.
schooldb.students table with ID, name, age, and course columns.PreparedStatement.ResultSet.Select the correct answer for each question.