OCPJP tests four interfaces and one class in package java.sql.*
JDBC API |
Four interfaces:
- Driver: The interface that every driver class must implement.
- Connection: A connection (session) with a specific database.
- Statement: The object used for executing a static SQL statement and returning the results it produces.
- 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:
- 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.