JDBC
JDBC is Java’s standard API for talking to relational databases like MySQL, PostgreSQL and SQL Server.
On this page · 5 min · Advanced
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Advanced
- Updated
- Oct 30, 2026
Related tutorials
In simple words#
JDBC is the telephone line between Java and the database: open a connection, speak a prepared question (PreparedStatement), listen to the answers row by row (ResultSet), hang up.
- Connection
- Session with the database.
- PreparedStatement
- SQL with ? parameters — safe and fast.
- ResultSet
- Rows returned by a query.
Learning objectives#
- Connect to a database
- Query with PreparedStatement
- Map ResultSet rows to records
- Use transactions
Explanation#
Add the driver dependency (e.g. com.microsoft.sqlserver:mssql-jdbc, org.postgresql:postgresql).
Get a Connection from DriverManager or, in real apps, a connection pool (HikariCP).
PreparedStatement with ? placeholders prevents SQL injection and handles types correctly.
conn.setAutoCommit(false) + commit/rollback groups changes into a transaction. Use try-with-resources for everything.
Code example: Querying products safely#
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
record Product(int id, String name, double price) {}
public class ProductDao {
private static final String URL =
"jdbc:sqlserver://localhost:1433;databaseName=ShopDB;encrypt=true;trustServerCertificate=true";
static List<Product> findCheaperThan(double maxPrice) throws SQLException {
String sql = "SELECT Id, Name, Price FROM Products WHERE Price < ? ORDER BY Price";
try (Connection conn = DriverManager.getConnection(URL, System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setDouble(1, maxPrice);
try (ResultSet rs = ps.executeQuery()) {
List<Product> list = new ArrayList<>();
while (rs.next()) list.add(new Product(rs.getInt("Id"), rs.getString("Name"), rs.getDouble("Price")));
return list;
}
}
}
public static void main(String[] args) throws SQLException {
findCheaperThan(5000).forEach(System.out::println);
}
}
Product[id=2, name=Mouse, price=1400.0] Product[id=3, name=Keyboard, price=2200.0]
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- Credentials come from environment variables.
- The ? placeholder is filled with setDouble.
- rs.next() moves through rows; columns map to a record.
- try-with-resources closes connection, statement and result set.
Real-world use case#
Lightweight services and batch jobs use JDBC (or JdbcTemplate) for fast, hand-written SQL.
Common mistakes#
"... WHERE name = '" + input + "'" invites SQL injection. Use PreparedStatement.
Use a connection pool such as HikariCP.
Best practices#
- PreparedStatement always
- Connection pool in apps
- try-with-resources
- Credentials from environment or vault
Remember this#
Connection → PreparedStatement → ResultSet.
? placeholders stop SQL injection.
Pool connections in real apps.
Practice exercise#
Your task: Insert a product with a PreparedStatement.
Show solution
try (var ps = conn.prepareStatement("INSERT INTO Products (Name, Price) VALUES (?, ?)")) {
ps.setString(1, "Webcam");
ps.setDouble(2, 3200);
ps.executeUpdate();
}
Mini quiz#
Which JDBC interface protects against SQL injection?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.