Sobes.tech
Junior — Middle

Explain what JDBC is and how it is used in Java to interact with databases.

sobes.tech AI

Answer from AI

JDBC (Java Database Connectivity) is a standard API in Java for interacting with databases. It allows executing SQL queries, retrieving results, and managing transactions.

Main components of JDBC:

  • DriverManager — manages database drivers.
  • Connection — establishes a connection to the database.
  • Statement / PreparedStatement — executes SQL queries.
  • ResultSet — stores query results.

Example of using JDBC to fetch data:

String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {
    String sql = "SELECT id, name FROM users WHERE active = ?";
    try (PreparedStatement stmt = conn.prepareStatement(sql)) {
        stmt.setBoolean(1, true);
        try (ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println(id + ": " + name);
            }
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Thus, JDBC acts as a bridge between a Java application and a database, providing a standardized way to work with data.

Explain what JDBC is and how it is used in Java to… - sobes.tech