JDBC: Connecting Java to Databases

Site Admin · 11 Sep 2026 · 14 views

Java Talks to a Database

JDBC (Java Database Connectivity) is the standard API for sending SQL statements from Java to a relational database. You need three things: the driver, the URL, and credentials.

The Standard Steps

  1. Load the database driver (handled automatically by the DriverManager).
  2. Open a connection with the URL and credentials.
  3. Create a statement.
  4. Execute a query or update.
  5. Process results and close everything.

A Complete Example

import java.sql.*;

String url = "jdbc:mysql://127.0.0.1:3306/school";
String user = "appuser";
String password = "secret";

try (Connection conn = DriverManager.getConnection(url, user, password);
     PreparedStatement ps = conn.prepareStatement(
         "SELECT id, name FROM students WHERE grade = ?")) {

    ps.setInt(1, 10);                 // parameters are safe against SQL injection
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " " + rs.getString("name"));
        }
    }
}

Always Use PreparedStatement

Building SQL by string concatenation opens the door to SQL injection. The ? placeholders bind values safely.

// Unsafe - never do this
String sql = "SELECT * FROM users WHERE name = '" + input + "'";

// Safe
PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM users WHERE name = ?");
ps.setString(1, input);

Inserts and Updates

try (PreparedStatement ps = conn.prepareStatement(
        "INSERT INTO students (name, grade) VALUES (?, ?)")) {
    ps.setString(1, "Nisha");
    ps.setInt(2, 9);
    int rows = ps.executeUpdate();   // number of affected rows
    System.out.println(rows + " row inserted");
}

Transactions

Multiple changes can be committed together so the database never shows a half-completed update:

conn.setAutoCommit(false);
try {
    // ... several statements ...
    conn.commit();
} catch (SQLException e) {
    conn.rollback();   // undo everything
}

JDBC architecture

JDBC layers

JDBC-ODBC bridge

JDBC type 2 driver

JDBC type 3 driver

JDBC type 4 driver

JDBC user interface

Key Points

  • JDBC needs a driver jar for the specific database (MySQL, PostgreSQL...).
  • Always use PreparedStatement with parameters.
  • Wrap resources in try-with-resources so connections close reliably.
Share this post:

Comments (0)

Please login or register to comment.