連線 java.sql.DriverManager

這是最簡單的連線方式。

首先,驅動程式必須使用 java.sql.DriverManager 註冊,以便它知道要使用哪個類。
這是通過載入驅動程式類來完成的,通常是。 java.lang.Class.forname( <driver class name> )

/**
 * Connect to a PostgreSQL database.
 * @param url the JDBC URL to connect to; must start with "jdbc:postgresql:"
 * @param user the username for the connection
 * @param password the password for the connection
 * @return a connection object for the established connection
 * @throws ClassNotFoundException if the driver class cannot be found on the Java class path
 * @throws java.sql.SQLException if the connection to the database fails
 */
private static java.sql.Connection connect(String url, String user, String password)
    throws ClassNotFoundException, java.sql.SQLException
{
    /*
     * Register the PostgreSQL JDBC driver.
     * This may throw a ClassNotFoundException.
     */
    Class.forName("org.postgresql.Driver");
    /*
     * Tell the driver manager to connect to the database specified with the URL.
     * This may throw an SQLException.
     */
    return java.sql.DriverManager.getConnection(url, user, password);
}

並非使用者和密碼也可以包含在 JDBC URL 中,在這種情況下,你不必在 getConnection 方法呼叫中指定它們。