Site Search:

Describe the interfaces that make up the core of the JDBC API including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations

Back>

OCPJP tests four interfaces and one class in package java.sql.*

JDBC API
JDBC API

Four interfaces:

  1. Driver: The interface that every driver class must implement.
  2. Connection: A connection (session) with a specific database.
  3. Statement: The object used for executing a static SQL statement and returning the results it produces.
  4. ResultSet: A table of data that representing a database result set, which is usually generated by executing a statement that queries the database.
One Factory Class:
  1. DriverManager: The basic service for managing a set of database drivers.
There are many database vendors: mysql, mariadb, postgresql, oracle, derby etc. In order to connect to a particular database, we need to specify the vendor specific JDBC driver in the classpath. These vendor specific JDBC drivers have concrete driver class implementing java.sql.Driver interface.

For example,  mysql's driver is something like mysql-connector-java-5.1.41.jar, we include it in the classpath like

javac -cp "/download/mysql-connector-java-5.1.41/mysql-connector-java-5.1.41-bin.jar:." MysqlTest.java
java -cp "/download/mysql-connector-java-5.1.41/mysql-connector-java-5.1.41-bin.jar:." MysqlTest

For another example, derby embedded sql driver is something like derby.jar, we include it in the classpth like:

javac -cp "$JAVA_HOME/db/lib/derby.jar:." DerbyTest.java 
java -cp "$JAVA_HOME/db/lib/derby.jar:." DerbyTest

In the following program, we connect to a derby database named people then select a column of a table.

import java.sql.*;

public class JDBCTest {
    static final String url = "jdbc:oracle:thin://localhost:1521/map";
    public static void main(String...args) throws SQLException {
        try(Connection conn = DriverManager.getConnection(url);
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("select name for city");) {
            while(rs.next()) {
                System.out.println(rs.getString("name"));
            }
        }
    }

}


DriverManager returns an instance of the Class in vendor's jar (following the url) that implements Connection interface.