Connecting with java.sql.DriverManager

suggest change

This is the simplest way to connect.

First, the driver has to be registered with java.sql.DriverManager so that it knows which class to use.

This is done by loading the driver class, typically with 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);
}

Not that user and password can also be included in the JDBC URL, in which case you don’t have to specify them in the getConnection method call.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents