Skip to lesson

JDBC URL, user and password

A Java program cannot reach a database until it knows where the database is, which one to open, who is logging in and the password. Where does each fact go, and what happens when one is wrong?

Reading jdbc:mysql://localhost:3306/shoplite part by part

A JDBC URL is the address DriverManager uses to choose a driver and reach one database, written as jdbc:mysql://host:port/database. It looks like a web address with jdbc: in front.

Split three URLs into their product, host, port, database and options.

The URL jdbc:mysql://localhost:3306/shoplite split into five parts. jdbc names the API. mysql tells DriverManager which driver to use. localhost is the computer where the database runs. 3306 is the port. shoplite is the database name.

Example 1 · Splitting a JDBC URL into its parts

JdbcUrlPartsDemo.javaJava
import java.net.URI;
public class JdbcUrlPartsDemo {    static void explain(String jdbcUrl) {        System.out.println(jdbcUrl);        if (!jdbcUrl.startsWith("jdbc:")) {            System.out.println("  not a JDBC URL: it must start with jdbc:");            return;        }        URI uri = URI.create(jdbcUrl.substring("jdbc:".length()));        System.out.println("  product:  " + uri.getScheme());        System.out.println("  host:     " + uri.getHost());        System.out.println("  port:     " + (uri.getPort() == -1 ? "(default 3306)" : uri.getPort()));        System.out.println("  database: " + uri.getPath().substring(1));        System.out.println("  options:  " + (uri.getQuery() == null ? "(none)" : uri.getQuery()));    }
    public static void main(String[] args) {        explain("jdbc:mysql://localhost:3306/shoplite");        explain("jdbc:mysql://192.168.1.20/shoplite?sslMode=REQUIRED&serverTimezone=Asia/Kolkata");        explain("mysql://localhost:3306/shoplite");    }}
Output
jdbc:mysql://localhost:3306/shoplite
  product:  mysql
  host:     localhost
  port:     3306
  database: shoplite
  options:  (none)
jdbc:mysql://192.168.1.20/shoplite?sslMode=REQUIRED&serverTimezone=Asia/Kolkata
  product:  mysql
  host:     192.168.1.20
  port:     (default 3306)
  database: shoplite
  options:  sslMode=REQUIRED&serverTimezone=Asia/Kolkata
mysql://localhost:3306/shoplite
  not a JDBC URL: it must start with jdbc:

What this code does

  • Removing the jdbc: prefix leaves text that java.net.URI can read like a web address: scheme, host, port, path and query.
  • The second URL has no port, so getPort() returns -1 and the driver would use 3306. The third URL has no jdbc: prefix, which is exactly what makes DriverManager say "No suitable driver".

localhost means "this same computer"; a server elsewhere uses its name or IP address. The database name works like USE shoplite; in the mysql client.

The port is the part learners get wrong most often. With two MySQL versions installed, or another port chosen in the installer, MySQL may listen on 3307 or 3308. SELECT @@port; in the mysql client shows the real one.

URL options: serverTimezone, characterEncoding and sslMode

URL options, also called connection properties, are name=value pairs written after a ? in a JDBC URL and joined with &, such as ?sslMode=REQUIRED&serverTimezone=Asia/Kolkata. Names are case-sensitive and unknown names are ignored.

Six variants of the same URL show which options take effect and which fail.

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

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

UrlOptions.javaJava
package com.shoplite.app;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class UrlOptions {    static final String BASE = "jdbc:mysql://localhost:3306/shoplite";
    public static void main(String[] args) {        check(BASE);        check(BASE + "?sslMode=REQUIRED&serverTimezone=Asia/Kolkata&characterEncoding=UTF-8");        check(BASE + "?sslMode=DISABLED");        check(BASE + "?sslmode=DISABLED");        check(BASE + "?sslMode=REQUIRED?serverTimezone=Asia/Kolkata");        check(BASE + "?serverTimezone=IST");    }
    static void check(String url) {        System.out.println(url.substring(BASE.length()).isEmpty() ? "(no options)" : url.substring(BASE.length()));        try (Connection conn = DriverManager.getConnection(url,                System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SHOW SESSION STATUS LIKE 'Ssl_cipher'")) {            rs.next();            String cipher = rs.getString(2);            System.out.println("  connected, encryption: " + (cipher.isEmpty() ? "OFF" : cipher));        } catch (SQLException e) {            System.out.println("  failed: " + e.getMessage());            if (e.getCause() != null && !e.getMessage().equals(e.getCause().getMessage())) {                System.out.println("  cause:  " + e.getCause().getMessage());            }        }    }}
Sample output
(no options)
  connected, encryption: TLS_AES_128_GCM_SHA256
?sslMode=REQUIRED&serverTimezone=Asia/Kolkata&characterEncoding=UTF-8
  connected, encryption: TLS_AES_128_GCM_SHA256
?sslMode=DISABLED
  connected, encryption: OFF
?sslmode=DISABLED
  connected, encryption: TLS_AES_128_GCM_SHA256
?sslMode=REQUIRED?serverTimezone=Asia/Kolkata
  failed: The connection property 'sslMode' acceptable values are: 'DISABLED', 'PREFERRED', 'REQUIRED', 'VERIFY_CA' or 'VERIFY_IDENTITY'. The value 'REQUIRED?serverTimezone=Asia/Kolkata' is not acceptable.
?serverTimezone=IST
  failed: Could not create connection to database server.
  cause:  Unknown time-zone ID: IST

What this code does

  • With no options the connection is already encrypted, because sslMode=PREFERRED is the default and MySQL 8 servers support TLS. sslmode in lower case is ignored, so encryption stays on.
  • A second ? makes the rest part of the value (REQUIRED?serverTimezone=...), and IST is not a time zone id Java knows. Both fail before any SQL runs.
  • sslMode=DISABLED worked here because the server had already seen this user over an encrypted connection. On a fresh login it fails with Public Key Retrieval is not allowed, covered in the next lesson.

The options you will meet most:

  • sslMode decides encryption of the network traffic. PREFERRED (the default) encrypts when the server can, REQUIRED refuses unencrypted connections, VERIFY_CA and VERIFY_IDENTITY also check the server's certificate, and DISABLED turns encryption off.
  • serverTimezone tells the driver the server's time zone, so date-time values convert correctly. Use a full zone id such as Asia/Kolkata or UTC, never IST. Driver versions before 8.0.23 failed without it on some computers, which is why old tutorials always add it.
  • characterEncoding=UTF-8 names the text encoding using Java's name. Current drivers already use MySQL's utf8mb4 with MySQL 8, so it mainly documents intent; UTF8MB4 is not a Java name and fails.

Keep the URL short: add an option only when you know why you need it.

Fix the error

Fix the URL option

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

Round 1 of 2

The second option is joined to the first with the wrong character.

String base = "jdbc:mysql://localhost:3306/shoplite";
String url = base
+ "?sslMode=REQUIRED?serverTimezone=Asia/Kolkata";

Error

The connection property 'sslMode' acceptable values are: 'DISABLED', 'PREFERRED', 'REQUIRED', 'VERIFY_CA' or 'VERIFY_IDENTITY'. The value 'REQUIRED?serverTimezone=Asia/Kolkata' is not acceptable.

Creating the shoplite database from the SQL section's script

Load the ShopLite script once, as root, from the folder that holds shoplite.sql.

Example 3 · Loading shoplite.sql as root

Runs in: the shoplite-database folder from the SQL section, with MySQL running

Terminal
mysql -u root -p < shoplite.sql
Sample output
Enter password: ********
customers	addresses	categories	products	orders	order_items
8	9	7	15	16	28

What this code does

  • < feeds the file to the client as if you typed it. When the input is a file, the client prints results as tab-separated text instead of boxed tables.
  • The counts 8, 9, 7, 15, 16 and 28 match the seed data. Any other numbers mean the script stopped early; scroll up for the first ERROR line.

The ShopLite database is the one you built in the SQL section's mini projects: six tables (customers, addresses, categories, products, orders, order_items) plus seed data, all in shoplite.sql. JDBC does not create it, so it must exist before a Java program can connect.

The script drops and recreates the tables, so running it again resets the data to the seed rows. Use Command Prompt on Windows or Terminal on macOS, because PowerShell does not support <; inside the mysql client, SOURCE C:/Users/you/shoplite-database/shoplite.sql; does the same with forward slashes. If the computer says mysql is not found, add MySQL's bin folder to PATH as the SQL section's install lesson showed.

A dedicated application user with CREATE USER and GRANT

An application user is a MySQL login made only for one program, with only the rights that program needs. ShopLite gets its own, shoplite_app, instead of using root.

Create shoplite_app with CREATE USER and GRANT, which you met in the SQL section.

Example 4 · Creating shoplite_app in the mysql client

Runs in: the mysql client, logged in as root

Terminal
mysql -u root -pCREATE USER 'shoplite_app'@'localhost' IDENTIFIED BY 'Shop#Lite2026';GRANT SELECT, INSERT, UPDATE, DELETE ON shoplite.* TO 'shoplite_app'@'localhost';SHOW GRANTS FOR 'shoplite_app'@'localhost';
Sample output
Enter password: ********
...
mysql> CREATE USER 'shoplite_app'@'localhost' IDENTIFIED BY 'Shop#Lite2026';
Query OK, 0 rows affected (0.36 sec)

mysql> GRANT SELECT, INSERT, UPDATE, DELETE ON shoplite.* TO 'shoplite_app'@'localhost';
Query OK, 0 rows affected (0.39 sec)

mysql> SHOW GRANTS FOR 'shoplite_app'@'localhost';
+------------------------------------------------------------------------------------+
| Grants for shoplite_app@localhost                                                  |
+------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `shoplite_app`@`localhost`                                   |
| GRANT SELECT, INSERT, UPDATE, DELETE ON `shoplite`.* TO `shoplite_app`@`localhost` |
+------------------------------------------------------------------------------------+
2 rows in set (0.03 sec)

What this code does

  • USAGE ON *.* means "may log in, nothing else"; the second line adds the four data rights on every table in shoplite, including tables created later.
  • If CREATE USER fails with error 1396, the user already exists: use DROP USER IF EXISTS first, or keep the existing one and only run GRANT.

Four choices in this script:

  • Why not root: if the app's password leaks, an attacker gets only this user's rights. With root, every database on the server is open.
  • No CREATE, DROP or ALTER: a bug or an attacker cannot delete tables. Schema changes are run by you, as root.
  • 'localhost' lets the user log in only from the same computer; the app and MySQL run on your laptop.
  • The password in the example is only an example. Pick your own, and never reuse your root password.

Checking the same URL, user and password in the mysql client first

Before debugging Java, log in with the mysql client using the same host, port, user and database as the JDBC URL.

Example 5 · Logging in as shoplite_app with the JDBC URL's details

Runs in: the mysql client

Terminal
mysql -h 127.0.0.1 -P 3306 -u shoplite_app -p shopliteSELECT CURRENT_USER(), DATABASE();SELECT COUNT(*) FROM products;DROP TABLE products;
Sample output
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Server version: 8.4.6 MySQL Community Server - GPL
...
mysql> SELECT CURRENT_USER(), DATABASE();
+------------------------+------------+
| CURRENT_USER()         | DATABASE() |
+------------------------+------------+
| shoplite_app@localhost | shoplite   |
+------------------------+------------+
1 row in set (0.01 sec)

mysql> SELECT COUNT(*) FROM products;
+----------+
| COUNT(*) |
+----------+
|       15 |
+----------+
1 row in set (0.21 sec)

mysql> DROP TABLE products;
ERROR 1142 (42000): DROP command denied to user 'shoplite_app'@'localhost' for table 'products'

What this code does

  • Each option matches one part of jdbc:mysql://127.0.0.1:3306/shoplite plus the user and password, so a successful login proves the Java settings are right.
  • DROP TABLE fails with error 1142: least privilege works. The app can read and change rows but cannot destroy the schema.

If the client cannot log in either, the problem is MySQL or the user, not your code. If the client works and Java fails, compare the JDBC URL with the client command letter by letter.

The client takes the facts as -h, -P (capital P), -u with -p, and the database name at the end. Use -h 127.0.0.1: it connects over TCP like the JDBC driver, while -h localhost may use a local socket file and hide a port problem.

Next step

Check your understanding

11 quick questions