← Chapter 10 — Threads, Networking & JDBC

36. JDBC Database Connectivity

mixed

Description

JDBC is Java's standard API for working with relational databases. A JDBC driver connects Java to a specific database system such as MySQL or PostgreSQL.

Use PreparedStatement for values supplied by users or variables. It separates SQL code from data and helps prevent SQL injection.

Subtopics

Connections

Description

A Connection represents a database session.

Explanation

DriverManager can create one from a database URL and credentials.

Example

java.sql.Connection con = java.sql.DriverManager.getConnection(url, user, password);

Prepared statements

Description

PreparedStatement safely binds values.

Explanation

Question marks mark values that are set separately.

Example

statement.setString(1, "Aditi");

Explanation

Use try-with-resources for Connection, PreparedStatement, and ResultSet so they close even when an error occurs. Store credentials outside source code, for example in environment-based configuration.

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class JdbcDemo {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/school";
        try (Connection con = DriverManager.getConnection(url, "user", "password");
             PreparedStatement statement = con.prepareStatement("SELECT * FROM students WHERE name = ?")) {
            statement.setString(1, "Aditi");
            System.out.println("Query prepared");
        }
    }
}

Key points

  • JDBC connects Java to databases.
  • PreparedStatement binds values safely.
  • Close database resources automatically.

Video

Open video

Open reference