Sobes.tech
Junior — Middle

Can you explain what Java Database Connectivity (JDBC) is?

sobes.tech AI

Answer from AI

Java Database Connectivity (JDBC) is an API in Java that allows programs to interact with various databases. With JDBC, you can execute SQL queries, retrieve results, and manage transactions.

Main components of JDBC:

  • DriverManager — manages the list of database drivers.
  • Connection — establishes a connection to the database.
  • Statement and PreparedStatement — execute SQL queries.
  • ResultSet — stores query results.

Example of simple connection and query:

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

            while (rs.next()) {
                System.out.println(rs.getString("name") + " - " + rs.getInt("age"));
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Can you explain what Java Database Connectivity… - sobes.tech