Skip to lesson

Practice: connecting to a database

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Connecting fails in a few ways, and each leaves a clear fingerprint: a URL slip, a missing driver, a stopped server, a refused login or a missing setting. Can you read the fingerprint and fix the right layer?

JDBC URLs: the shape and the usual slips

A checker reviews six URLs, each with a different slip or none at all.

Example 1 · A URL checker for the usual slips

UrlReview.javaJava
import java.net.URI;
public class UrlReview {    static String review(String url) {        if (!url.startsWith("jdbc:mysql://")) {            return "must start with jdbc:mysql://";        }        if (url.indexOf('?') != url.lastIndexOf('?')) {            return "only one ? allowed; join options with &";        }        URI uri;        try {            uri = URI.create(url.substring("jdbc:".length()));        } catch (IllegalArgumentException e) {            return "not a valid address: " + e.getMessage();        }        if (uri.getHost() == null) {            return "host or port is not valid";        }        if (uri.getPath() == null || uri.getPath().length() <= 1) {            return "no database name after the port";        }        int port = uri.getPort() == -1 ? 3306 : uri.getPort();        return "OK: host " + uri.getHost() + ", port " + port + ", database " + uri.getPath().substring(1);    }
    public static void main(String[] args) {        String base = "jdbc:mysql://localhost:3306/shoplite";        String[] urls = {            base,            base.replace(":3306", ""),            base.replace("shoplite", ""),            base.replace("3306", "33o6"),            base + "?sslMode=REQUIRED?serverTimezone=UTC",            base.replaceFirst("/{2}", "/")        };        for (String url : urls) {            System.out.println(url);            System.out.println("  " + review(url));        }    }}
Output
jdbc:mysql://localhost:3306/shoplite
  OK: host localhost, port 3306, database shoplite
jdbc:mysql://localhost/shoplite
  OK: host localhost, port 3306, database shoplite
jdbc:mysql://localhost:3306/
  no database name after the port
jdbc:mysql://localhost:33o6/shoplite
  host or port is not valid
jdbc:mysql://localhost:3306/shoplite?sslMode=REQUIRED?serverTimezone=UTC
  only one ? allowed; join options with &
jdbc:mysql:/localhost:3306/shoplite
  must start with jdbc:mysql://

What this code does

  • Each check matches one slip: the prefix, a second ?, a port that is not a number (then URI cannot find a host), and an empty database name. A URL without a port is fine and uses 3306.
  • jdbc:mysql:/localhost has only one /, so it fails the prefix check; the driver would answer No suitable driver found. The replace calls in main build each slip from one base URL.

Every MySQL JDBC URL has the same shape: jdbc:mysql://host:port/database?name=value&name=value, and most connection bugs on a first project are one character away from it. Review: JDBC URL, user and password (opens in a new tab).

A slip in the prefix gives No suitable driver found; a slip in an option gives a driver error or, for a wrong-case name, silently nothing. Checking the URL in code at startup turns all of these into one clear message.

Fix the error

Fix the URL slip

Read the real error, then pick the line that fixes it.

Round 1 of 2

The driver is loaded, but the URL has one slash too few.

String url = "jdbc:mysql:/localhost:3306/shoplite";
Connection conn = DriverManager.getConnection(url, user, password);

Error

No suitable driver found for jdbc:mysql:/localhost:3306/shoplite

Reading a connection error from its message

Match the first words of each message to the layer that failed, then fix that layer only.

Example 2 · Matching messages to the layer that failed

ErrorTriage.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class ErrorTriage {    // First words of the message -> where the problem is and what to check    static final Map<String, String> CAUSES = new LinkedHashMap<>();
    static {        CAUSES.put("No suitable driver found", "Java side: driver missing from the classpath, or URL typo");        CAUSES.put("The url cannot be null", "Java side: DB_URL not set");        CAUSES.put("Communications link failure", "network: MySQL stopped, wrong host or wrong port");        CAUSES.put("Public Key Retrieval is not allowed", "login: SSL turned off, remove sslMode=DISABLED");        CAUSES.put("Access denied for user", "login: wrong user/password, or no rights on the database");        CAUSES.put("Unknown database", "server: the database name in the URL does not exist");    }
    static String triage(String message) {        for (Map.Entry<String, String> cause : CAUSES.entrySet()) {            if (message.startsWith(cause.getKey())) {                if (message.contains("(using password: NO)")) {                    return "login: no password was sent, the setting is missing";                }                return cause.getValue();            }        }        return "unknown: read the whole message and its cause";    }
    public static void main(String[] args) {        String[] messages = {            "No suitable driver found for jdbc:mysql//localhost:3306/shoplite",            "Communications link failure",            "Access denied for user 'shoplite_app'@'localhost' (using password: YES)",            "Access denied for user 'asha'@'localhost' (using password: NO)",            "Access denied for user 'shoplite_app'@'localhost' to database 'shoplit'",            "Unknown database 'shoplit'",            "Public Key Retrieval is not allowed",            "The url cannot be null"        };        for (String m : messages) {            System.out.println(m);            System.out.println("  -> " + triage(m));        }    }}
Output
No suitable driver found for jdbc:mysql//localhost:3306/shoplite
  -> Java side: driver missing from the classpath, or URL typo
Communications link failure
  -> network: MySQL stopped, wrong host or wrong port
Access denied for user 'shoplite_app'@'localhost' (using password: YES)
  -> login: wrong user/password, or no rights on the database
Access denied for user 'asha'@'localhost' (using password: NO)
  -> login: no password was sent, the setting is missing
Access denied for user 'shoplite_app'@'localhost' to database 'shoplit'
  -> login: wrong user/password, or no rights on the database
Unknown database 'shoplit'
  -> server: the database name in the URL does not exist
Public Key Retrieval is not allowed
  -> login: SSL turned off, remove sslMode=DISABLED
The url cannot be null
  -> Java side: DB_URL not set

What this code does

  • A LinkedHashMap keeps the message starts in a fixed order, and startsWith finds the first that matches.
  • The using password: NO case is checked inside the Access denied match, because it points to a missing setting, not a wrong password.

No suitable driver found and The url cannot be null come from the Java side, before any network traffic. Communications link failure is the network: check the root cause for Connection refused (server stopped or wrong port) or UnknownHostException (wrong host). Access denied, Unknown database and Public Key Retrieval is not allowed come back from a server that was reached, so the URL's host and port are already right. Review: DriverManager and Connection (opens in a new tab).

Access denied ... (using password: NO) with your computer's user name is a Java-side problem in disguise: the user and password settings were never set.

Settings: hard-coded, missing or wrong

Three settings maps are reviewed: a good laptop, a lab PC and a fresh clone.

Example 3 · Finding missing, empty and wrong settings

SettingsReview.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;
public class SettingsReview {    static List<String> problems(Map<String, String> settings) {        List<String> found = new ArrayList<>();        for (String name : List.of("DB_URL", "DB_USER", "DB_PASSWORD")) {            String value = settings.get(name);            if (value == null) {                found.add(name + " is missing");            } else if (value.isBlank()) {                found.add(name + " is empty");            } else if (!value.equals(value.trim())) {                found.add(name + " has spaces at the start or end");            }        }        String user = settings.getOrDefault("DB_USER", "").trim();        if (user.equals("root")) {            found.add("the app logs in as root; use shoplite_app");        }        return found;    }
    static void report(String label, Map<String, String> settings) {        List<String> found = problems(settings);        System.out.println(label + ": " + (found.isEmpty() ? "OK" : found.size() + " problem(s)"));        found.forEach(p -> System.out.println("  - " + p));    }
    public static void main(String[] args) {        report("Laptop", Map.of(                "DB_URL", "jdbc:mysql://localhost:3306/shoplite",                "DB_USER", "shoplite_app",                "DB_PASSWORD", "Shop#Lite2026"));        report("Lab PC", Map.of(                "DB_URL", "jdbc:mysql://localhost:3306/shoplite",                "DB_USER", "root",                "DB_PASSWORD", ""));        report("New clone", Map.of(                "DB_USER", "shoplite_app "));    }}
Output
Laptop: OK
Lab PC: 2 problem(s)
  - DB_PASSWORD is empty
  - the app logs in as root; use shoplite_app
New clone: 3 problem(s)
  - DB_URL is missing
  - DB_USER has spaces at the start or end
  - DB_PASSWORD is missing

What this code does

  • problems checks each setting for missing, empty and padded values, then flags root as the user. All problems are collected before reporting.
  • The "New clone" case is a fresh git clone with no settings yet: one run shows all three problems instead of failing three times.

Settings go wrong in three ways. Hard-coded values work on one laptop and leak into Git. Missing values become null and produce confusing errors far from the cause. Wrong values, such as an empty password, a trailing space or the root user, connect badly or connect with too many rights.

The fix is always the same: read every setting from the environment or db.properties, check them all at startup, and report every problem in one message before trying to connect. Review: Keeping credentials out of code (opens in a new tab).

Find the bug

Find the settings bug

Tap the line that is the problem.

The code must keep the password out of Git.

Round 1 of 3

Printing database details with DatabaseMetaData

Print the server, driver, user, database and tables the program really connects to.

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

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

DbInfo.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;
public class DbInfo {    public static void main(String[] args) throws SQLException {        try (Connection conn = DriverManager.getConnection(System.getenv("DB_URL"),                System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            DatabaseMetaData meta = conn.getMetaData();            System.out.println("Product:  " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());            System.out.println("Driver:   " + meta.getDriverName() + " " + meta.getDriverMajorVersion()                    + "." + meta.getDriverMinorVersion());            System.out.println("JDBC:     " + meta.getJDBCMajorVersion() + "." + meta.getJDBCMinorVersion());            System.out.println("User:     " + meta.getUserName());            System.out.println("Database: " + conn.getCatalog());
            System.out.println("Tables:");            try (ResultSet tables = meta.getTables(conn.getCatalog(), null, "%", new String[] {"TABLE"})) {                while (tables.next()) {                    System.out.println("  " + tables.getString("TABLE_NAME"));                }            }        }    }}
Sample output
Product:  MySQL 8.4.6
Driver:   MySQL Connector/J 26.7
JDBC:     4.2
User:     shoplite_app@localhost
Database: shoplite
Tables:
  addresses
  categories
  customers
  order_items
  orders
  products

What this code does

  • Every line comes from DatabaseMetaData or the connection; the program runs no SQL of its own. Versions on your computer will differ.
  • getTables returns a ResultSet with one row per table; the column TABLE_NAME holds the name. Six names mean shoplite.sql was loaded into this database.

getTables(catalog, null, "%", new String[] {"TABLE"}) lists the tables, which is a quick way to check that shoplite.sql was loaded into the right database.

A startup check that prints these lines makes most "it works on my machine" problems obvious from the first lines of output.

Finish up

Mark complete & continue

Next: Mini project: connect shoplite-console to MySQL