Skip to lesson

DriverManager and Connection

A shop's Java program must open a session with MySQL before it can read a single product. When that first step fails, how can the error message tell you whether the server, the login or the database name is wrong?

DriverManager.getConnection(url, user, password)

A Connection is one open, logged-in session with the database; every query of a program runs through one. DriverManager.getConnection(url, user, password) opens it and returns it.

Open one connection with the settings from three environment variables, and time how long it takes.

Example 1 · src/main/java/com/shoplite/app/ConnectOnce.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

ConnectOnce.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class ConnectOnce {    public static void main(String[] args) throws SQLException {        String url = System.getenv("DB_URL");        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        long start = System.nanoTime();        Connection conn = DriverManager.getConnection(url, user, password);        long millis = (System.nanoTime() - start) / 1_000_000;
        System.out.println("Connected in " + millis + " ms");        System.out.println("Object: " + conn.getClass().getName());        System.out.println("Open:   " + !conn.isClosed());        conn.close();    }}
Sample output
Connected in 2040 ms
Object: com.mysql.cj.jdbc.ConnectionImpl
Open:   true

What this code does

  • getConnection returned only after the network connection, the TLS handshake and the login were done; on this laptop that took about 2 seconds, and your number will differ.
  • The returned object is the driver's ConnectionImpl. The program closes it by hand at the end, which is skipped if an exception happens first; section 3 shows a safer way.

The call finds the driver for the URL, opens a network connection to MySQL, logs in and selects the database. That cost is why the Connection Pooling module later reuses connections instead of opening one per query. When anything goes wrong, the call throws SQLException, a checked exception, so main must declare it or catch it.

Watch for null arguments. A null URL fails with The url cannot be null. A null user is worse: the driver logs in with your computer's login name and no password, giving Access denied for user 'asha'@'localhost' (using password: NO). That is the usual sign that an environment variable was not set.

Checking the connection: isValid, getCatalog and DatabaseMetaData

DatabaseMetaData is the object returned by conn.getMetaData(). It describes the server and the driver: product name and version, driver name and version, the logged-in user and the URL.

Check that the connection works, then print which server, database and user it really uses.

Example 2 · src/main/java/com/shoplite/app/FirstConnection.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

FirstConnection.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.SQLException;
public class FirstConnection {    public static void main(String[] args) throws SQLException {        String url = System.getenv("DB_URL");        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        try (Connection conn = DriverManager.getConnection(url, user, password)) {            System.out.println("Connected:      " + conn.isValid(2));            System.out.println("Database:       " + conn.getCatalog());
            DatabaseMetaData meta = conn.getMetaData();            System.out.println("Server:         " + meta.getDatabaseProductName()                    + " " + meta.getDatabaseProductVersion());            System.out.println("Driver:         " + meta.getDriverName()                    + " " + meta.getDriverVersion());            System.out.println("Logged in as:   " + meta.getUserName());            System.out.println("URL:            " + meta.getURL());        }    }}
Sample output
Connected:      true
Database:       shoplite
Server:         MySQL 8.4.6
Driver:         MySQL Connector/J mysql-connector-j-26.7.0 (Revision: 559f62df01d4f618440da174ff45ba87f7b3b2a8)
Logged in as:   shoplite_app@localhost
URL:            jdbc:mysql://localhost:3306/shoplite

What this code does

  • isValid(2) waits at most 2 seconds for the server's reply. getCatalog() shows the database from the URL.
  • DatabaseMetaData gives the server and driver versions and the user as the server sees it (shoplite_app@localhost). The versions on your computer will differ.

isValid(seconds) suits a connection you have held for a while, because a fresh one from getConnection is already valid. JDBC calls a MySQL database a catalog, hence getCatalog().

Print these details once at startup. When a teammate says "it works on my machine", the first log lines show which server, database and user each of you really used.

Closing the connection, and a first look at try-with-resources

Try-with-resources is a try ( ... ) block that declares a resource in its header, so Java calls close() on it when the block ends, whether it ends normally or with an exception.

Close a connection by hand, then let try-with-resources do it, and check isClosed() each time.

Example 3 · src/main/java/com/shoplite/app/CloseDemo.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

CloseDemo.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class CloseDemo {    public static void main(String[] args) throws SQLException {        String url = System.getenv("DB_URL");        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        // The long way: close() by hand        Connection first = DriverManager.getConnection(url, user, password);        System.out.println("Before close: closed = " + first.isClosed());        first.close();        System.out.println("After close:  closed = " + first.isClosed());        try {            first.createStatement();        } catch (SQLException e) {            System.out.println("Using it now: " + e.getMessage());        }
        // The usual way: try-with-resources closes it for you        Connection kept;        try (Connection conn = DriverManager.getConnection(url, user, password)) {            kept = conn;            System.out.println("Inside try:   closed = " + conn.isClosed());        }        System.out.println("After try:    closed = " + kept.isClosed());    }}
Output
Before close: closed = false
After close:  closed = true
Using it now: No operations allowed after connection closed.
Inside try:   closed = false
After try:    closed = true

What this code does

  • After close(), isClosed() is true and creating a statement fails with No operations allowed after connection closed.
  • With try-with-resources the connection is open inside the block and closed right after it, without any close() call in your code. kept only shows that the object outlives the block.

close() ends the session: the server frees the thread and memory it kept for you, and the network connection is shut. A program that forgets to close leaks connections, and after enough of them MySQL refuses new ones with Too many connections; the Resource Handling & SQL Errors module shows that failure in full.

Find the bug

Which line uses a closed connection?

Tap the line that fails with "No operations allowed after connection closed."

The connection is closed by hand.

Round 1 of 2

Communications link failure: server not running, wrong host or port

The root cause is the last exception in the getCause() chain: the real reason behind a wrapper such as Communications link failure.

Two bad URLs, one with the wrong port and one with a misspelt host, fail with the same first line.

Four connection errors and their usual cause. Communications link failure: server off, or wrong host or port. Access denied for user: wrong user or password. Unknown database: not created or mistyped. No suitable driver found: driver missing or URL mistyped.

Example 4 · src/main/java/com/shoplite/app/LinkFailures.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

LinkFailures.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class LinkFailures {    public static void main(String[] args) {        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        tryConnect("jdbc:mysql://localhost:3307/shoplite", user, password);  // wrong port        tryConnect("jdbc:mysql://localhst:3306/shoplite", user, password);   // misspelt host    }
    static void tryConnect(String url, String user, String password) {        System.out.println("Trying " + url);        try (Connection conn = DriverManager.getConnection(url, user, password)) {            System.out.println("  connected");        } catch (SQLException e) {            System.out.println("  " + e.getClass().getSimpleName() + ", SQL state " + e.getSQLState());            System.out.println("  message: " + e.getMessage().lines().findFirst().orElse(""));            Throwable root = e;            while (root.getCause() != null) {                root = root.getCause();            }            System.out.println("  root cause: " + root);        }    }}
Sample output
Trying jdbc:mysql://localhost:3307/shoplite
  CommunicationsException, SQL state 08S01
  message: Communications link failure
  root cause: java.net.ConnectException: Connection refused: connect
Trying jdbc:mysql://localhst:3306/shoplite
  CommunicationsException, SQL state 08S01
  message: Communications link failure
  root cause: java.net.UnknownHostException: No such host is known (localhst)

What this code does

  • Both failures are CommunicationsException with SQL state 08S01 and the same first line. Only the root cause tells them apart: Connection refused for the wrong port, UnknownHostException for the misspelt host.
  • The exact root-cause text depends on the operating system; on macOS the first one reads java.net.ConnectException: Connection refused.

Communications link failure (SQL state 08S01) means the driver never managed to talk to a MySQL server. Connection refused also appears when MySQL is simply stopped. An IP address that does not answer at all makes the call hang until a timeout, which is why a wrong host can take several seconds to fail.

To check that MySQL is running, open the Services app on Windows (look for MySQL84 as Running) or System Settings, then MySQL, on macOS, and start the server if it is stopped.

Predict the output

What does the error say?

Pick what each program prints.

Round 1 of 2

MySQL listens on port 3306, but the URL says 3307.

String url = "jdbc:mysql://localhost:3307/shoplite";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("connected");
} catch (SQLException e) {
System.out.println(e.getSQLState());
}

Access denied, unknown database and Public Key Retrieval errors

An SQL state is a five-character code that classifies an error: 08... means connection problems and 28000 a failed login. getErrorCode() adds the database's own number, such as 1045.

Four connection attempts, with SSL off, a wrong password, a misspelt database and the default settings, each fail or succeed differently.

Example 5 · src/main/java/com/shoplite/app/LoginFailures.java

Runs in: the shoplite-console project, run right after creating shoplite_app (before its first login)

LoginFailures.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
public class LoginFailures {    public static void main(String[] args) {        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");        String base = "jdbc:mysql://localhost:3306/";
        tryConnect("SSL turned off", base + "shoplite?sslMode=DISABLED", user, password);        tryConnect("Wrong password", base + "shoplite", user, "shoplite123");        tryConnect("Misspelt database", base + "shoplit", user, password);        tryConnect("Default SSL", base + "shoplite", user, password);    }
    static void tryConnect(String label, String url, String user, String password) {        try (Connection conn = DriverManager.getConnection(url, user, password)) {            System.out.println(label + ": connected");        } catch (SQLException e) {            System.out.println(label + ": " + e.getMessage());            System.out.println("  SQL state " + e.getSQLState() + ", MySQL error " + e.getErrorCode());        }    }}
Sample output
SSL turned off: Public Key Retrieval is not allowed
  SQL state 08001, MySQL error 0
Wrong password: Access denied for user 'shoplite_app'@'localhost' (using password: YES)
  SQL state 28000, MySQL error 1045
Misspelt database: Access denied for user 'shoplite_app'@'localhost' to database 'shoplit'
  SQL state 42000, MySQL error 1044
Default SSL: connected

What this code does

  • The first attempt fails with Public Key Retrieval is not allowed because SSL is off and the server has not seen this user over an encrypted connection yet.
  • A wrong password gives error 1045; a misspelt database gives 1044 for an application user. With the default sslMode, the same user and password connect.

Read each message word by word: it names the user, the host it saw you from and often the database.

  • Access denied for user 'shoplite_app'@'localhost' (using password: YES), error 1045: wrong password or user name. using password: NO means the password was empty or null.
  • Access denied for user 'shoplite_app'@'localhost' to database 'shoplit', error 1044: a misspelt database name. MySQL does not tell a user about databases it has no rights on; root would see Unknown database 'shoplit', error 1049.
  • Public Key Retrieval is not allowed: MySQL 8's login method needs an encrypted connection or the server's public key, and sslMode=DISABLED stops the driver from fetching the key. Remove sslMode=DISABLED; allowPublicKeyRetrieval=true is acceptable only on your own laptop.

The Public Key error can look random: after one encrypted login the server remembers the user until it restarts, and the same URL suddenly works.

Next step

Check your understanding

12 quick questions