What is JDBC?
JDBC (Java Database Connectivity) is the standard Java API for talking to relational databases such as MySQL, PostgreSQL, Oracle and SQLite. Your code uses the interfaces in java.sql; a driver (a jar file from the database vendor) does the database-specific work.
| Database | Driver jar | URL example |
|---|---|---|
| SQLite | sqlite-jdbc | jdbc:sqlite:school.db |
| MySQL | mysql-connector-j | jdbc:mysql://localhost:3306/school |
| PostgreSQL | postgresql | jdbc:postgresql://localhost:5432/school |
SQLite needs no server: the whole database is one file, which makes it ideal for practice.
The five steps
- Add the driver jar to the classpath.
- Open a
ConnectionwithDriverManager.getConnection(url, user, password). - Create a
PreparedStatementwith SQL. - Execute it:
executeQuery()for SELECT,executeUpdate()for INSERT, UPDATE and DELETE. - Close everything; try-with-resources does it for you.
Connecting and creating a table
import java.sql.*;
public class SchoolDb {
static final String URL = "jdbc:sqlite:school.db";
public static void main(String[] args) throws SQLException {
try (Connection con = DriverManager.getConnection(URL);
Statement st = con.createStatement()) {
st.executeUpdate("""
CREATE TABLE IF NOT EXISTS student (
roll INTEGER PRIMARY KEY,
name TEXT NOT NULL,
marks INTEGER
)""");
System.out.println("Table ready");
}
}
}
Compile and run with the driver on the classpath, for example java -cp ".;sqlite-jdbc.jar" SchoolDb on Windows (use : instead of ; on Linux and macOS).
Insert with PreparedStatement
String sql = "INSERT INTO student (roll, name, marks) VALUES (?, ?, ?)";
try (Connection con = DriverManager.getConnection(URL);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, 101);
ps.setString(2, "Asha");
ps.setInt(3, 91);
int rows = ps.executeUpdate();
System.out.println(rows + " row inserted");
}
Each ? is a placeholder, filled by setInt, setString, setDouble, setDate and so on. Positions start at 1.
Read with ResultSet
try (Connection con = DriverManager.getConnection(URL);
PreparedStatement ps = con.prepareStatement(
"SELECT roll, name, marks FROM student WHERE marks >= ? ORDER BY marks DESC")) {
ps.setInt(1, 60);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.printf("%d %-8s %d%n",
rs.getInt("roll"), rs.getString("name"), rs.getInt("marks"));
}
}
}
A ResultSet starts before the first row; each rs.next() moves to the next row and returns false when there are no more.
Update and delete
try (Connection con = DriverManager.getConnection(URL);
PreparedStatement ps = con.prepareStatement("UPDATE student SET marks = ? WHERE roll = ?")) {
ps.setInt(1, 95);
ps.setInt(2, 101);
System.out.println(ps.executeUpdate() + " row updated");
}
DELETE FROM student WHERE roll = ? works the same way. executeUpdate returns how many rows changed.
Why PreparedStatement? SQL injection
Never build SQL by joining strings with user input:
// DANGEROUS
String sql = "SELECT * FROM users WHERE name = '" + name + "'";
If someone types ' OR '1'='1 as their name, the query returns every user. This attack is SQL injection. With a PreparedStatement, the value is sent separately from the SQL and is always treated as data, never as code. It is also faster when the same statement runs many times.
Transactions
By default every statement is committed immediately. For changes that must all succeed or all fail, such as moving money between two accounts, use a transaction:
try (Connection con = DriverManager.getConnection(URL)) {
con.setAutoCommit(false);
try (PreparedStatement debit = con.prepareStatement(
"UPDATE account SET balance = balance - ? WHERE id = ?");
PreparedStatement credit = con.prepareStatement(
"UPDATE account SET balance = balance + ? WHERE id = ?")) {
debit.setDouble(1, 500); debit.setInt(2, 1); debit.executeUpdate();
credit.setDouble(1, 500); credit.setInt(2, 2); credit.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback(); // undo both changes
throw e;
}
}
The DAO pattern
Keep SQL out of the rest of the program: a DAO (Data Access Object) class has methods such as save(Student s), findByRoll(int roll) and findAll(), and only it uses JDBC. The rest of the app works with Student objects.
Modern Java at a glance
| Version | Feature | Example |
|---|---|---|
| Java 8 | lambdas, streams, java.time, Optional | list.stream().filter(...) |
| Java 10 | var for local variables | var list = new ArrayList<String>(); |
| Java 11 | String.isBlank, strip, repeat; Files.readString | "ab".repeat(3) |
| Java 14 | switch expressions | case 1, 2 -> "low"; |
| Java 15 | text blocks | """ multi-line strings """ |
| Java 16 | records; pattern matching for instanceof | if (o instanceof String s) |
| Java 17 | sealed classes | sealed interface Shape permits Circle, Square |
| Java 21 | pattern matching for switch; record patterns; virtual threads | see below |
Pattern matching for switch (Java 21)
sealed interface Shape permits Circle, Square { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.side() * q.side();
};
}
Because Shape is sealed, the compiler knows these are the only two kinds, so no default is needed, and adding a new shape makes every incomplete switch a compile error.
Common mistakes
- Missing driver jar: "No suitable driver found for jdbc:...".
- Building SQL with
+and user input (SQL injection). - Starting
PreparedStatementparameter positions at 0; they start at 1. - Reading a
ResultSetwithout callingrs.next()first. - Not closing connections, so the database runs out of them; use try-with-resources.
Key points
- JDBC =
Connection,PreparedStatement,ResultSet, plus a vendor driver. executeQueryfor SELECT;executeUpdatefor INSERT, UPDATE, DELETE and DDL.- Always use
PreparedStatementwith?placeholders to prevent SQL injection. setAutoCommit(false),commit()androllback()make a group of changes all-or-nothing.- Modern Java adds
var, records, text blocks, switch expressions, sealed types and pattern matching.
Practice questions
1. Which method runs a SELECT, and which runs an INSERT?
executeQuery() for SELECT (returns a ResultSet); executeUpdate() for INSERT (returns the number of rows changed).
2. Write the code to delete the student with roll 105 using a PreparedStatement.
try (Connection con = DriverManager.getConnection(URL);
PreparedStatement ps = con.prepareStatement("DELETE FROM student WHERE roll = ?")) {
ps.setInt(1, 105);
System.out.println(ps.executeUpdate() + " row deleted");
}3. What is SQL injection, and how does PreparedStatement stop it?
SQL injection is when user input changes the meaning of an SQL query because it was pasted into the SQL text. A PreparedStatement sends the input separately as a parameter, so it is always treated as a value, never as SQL.
4. Print the number of students with marks below 40.
try (Connection con = DriverManager.getConnection(URL);
PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM student WHERE marks < 40");
ResultSet rs = ps.executeQuery()) {
rs.next();
System.out.println(rs.getInt(1));
}5. Why turn off auto-commit for a money transfer?
So the debit and the credit form one transaction: if either fails, rollback() undoes both, and money is never lost or created.