Sobes.tech
Junior — Middle

How does Java interact with a database through JDBC?

sobes.tech AI

Answer from AI

Java interacts with databases through JDBC (Java Database Connectivity) — an API that allows executing SQL queries and managing results.

Main steps of interaction:

  1. Loading the database driver.
  2. Establishing a connection to the database via DriverManager.getConnection().
  3. Creating a Statement or PreparedStatement object to execute SQL queries.
  4. Executing queries using executeQuery() (for SELECT) or executeUpdate() (for INSERT, UPDATE, DELETE).
  5. Processing results through the ResultSet object.
  6. Closing resources (ResultSet, Statement, Connection) to free memory.

Example:

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "password";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {

            stmt.setInt(1, 1);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                System.out.println("User: " + rs.getString("name"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Thus, JDBC provides a standardized way to work with various DBMS from Java applications.