Java JDBC Setup
Java JDBC setup means getting three things ready: a JDK, a JDBC driver for your database, and a database your program can reach. The JDBC API itself ships with the JDK, but the driver is a separate JAR file that you must add to your project.
In this lesson you will add the H2 and MySQL drivers with Maven, Gradle or a plain JAR file, check that the driver is found, prepare a MySQL database and user, keep connection settings out of your code, and build a small tool that tests the whole setup.
What You Need for Java JDBC Setup
| Requirement | Why | How to check |
|---|---|---|
| JDK 17 or newer | Compiles and runs your code; contains java.sql | java -version |
| A JDBC driver JAR | Translates JDBC calls for one database | Listed in your build file or classpath |
| A database | Stores the data | H2 needs nothing; MySQL/PostgreSQL need a running server |
| Connection details | URL, user name, password | From your database setup |
Check your JDK from a terminal:
java -version
javac -version
Output (your version numbers may differ):
openjdk version "25" 2025-09-16
javac 25
Any JDK from 17 upward runs every example in this tutorial. If javac is not found, revisit the Install JDK lesson earlier in this tutorial.
Note: You do not need to download anything to use the JDBC interfaces.
java.sql.Connection,StatementandResultSetare already part of the JDK. Only the driver is extra.
Choosing a JDBC Driver
Every database has its own driver. The driver JAR must match the database you connect to, and its URL prefix tells DriverManager which driver to use.
| Database | Maven coordinates (groupId:artifactId) | Driver class | URL prefix |
|---|---|---|---|
| H2 | com.h2database:h2 | org.h2.Driver | jdbc:h2: |
| MySQL | com.mysql:mysql-connector-j | com.mysql.cj.jdbc.Driver | jdbc:mysql: |
| PostgreSQL | org.postgresql:postgresql | org.postgresql.Driver | jdbc:postgresql: |
| SQLite | org.xerial:sqlite-jdbc | org.sqlite.JDBC | jdbc:sqlite: |
| SQL Server | com.microsoft.sqlserver:mssql-jdbc | com.microsoft.sqlserver.jdbc.SQLServerDriver | jdbc:sqlserver: |
Note: The old MySQL artifact
mysql:mysql-connector-javaand the driver classcom.mysql.jdbc.Driverare outdated. Usecom.mysql:mysql-connector-jandcom.mysql.cj.jdbc.Driver.
Add the JDBC Driver with Maven
In a Maven project, add the driver as a dependency in pom.xml. Maven downloads the JAR and puts it on the classpath for you.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gocourse</groupId>
<artifactId>jdbc-demo</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
</properties>
<dependencies>
<!-- H2: embedded database, perfect for learning and tests -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.4.240</version>
</dependency>
<!-- MySQL driver: add when you connect to a MySQL server -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.6.0</version>
</dependency>
</dependencies>
</project>
How it works:
- Each
<dependency>names one driver by its group, artifact and version. maven.compiler.releasesets the Java version your code is compiled for.- Run
mvn compileand Maven downloads both JARs into your local repository (~/.m2). - Check Maven Central for newer versions before you start a new project.
Note: Your code only calls
java.sqlinterfaces, so you can mark a driver with<scope>runtime</scope>. It is then available when the program runs but cannot be used by accident in your source code.
Add the JDBC Driver with Gradle
In a Gradle project, add the same coordinates to build.gradle (Groovy DSL):
plugins {
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.h2database:h2:2.4.240'
runtimeOnly 'com.mysql:mysql-connector-j:9.6.0'
}
application {
mainClass = 'DriverCheck'
}
How it works:
mavenCentral()tells Gradle where to download the JARs.implementationmakes H2 available at compile time and run time, which you need if you use H2 classes directly (such as itsDataSource).runtimeOnlyadds the MySQL driver only when the program runs, because your code talks to it only throughjava.sqlinterfaces.gradle rundownloads the drivers, compiles and startsDriverCheck.
Use a Driver JAR Without a Build Tool
For small experiments you can download the driver JAR (for example h2-2.4.240.jar from Maven Central) and pass it on the classpath with -cp.
# Linux and macOS: classpath entries are separated by ':'
javac -cp .:h2-2.4.240.jar DriverCheck.java
java -cp .:h2-2.4.240.jar DriverCheck
# Windows: classpath entries are separated by ';'
javac -cp .;h2-2.4.240.jar DriverCheck.java
java -cp .;h2-2.4.240.jar DriverCheck
# Single-file programs can skip javac (Java 11+)
java -cp h2-2.4.240.jar DriverCheck.java
How it works:
.adds the current folder, where your compiled.classfiles are.- The JAR file adds the driver classes.
- If you forget the JAR, the code still compiles (it only uses
java.sql), but at run time you getNo suitable driver found.
Check Which JDBC Drivers Are Loaded
Since JDBC 4.0, a driver JAR contains a file named META-INF/services/java.sql.Driver that lists its driver class. DriverManager reads this file and registers the driver automatically. This program lists every driver that was found.
import java.sql.Driver;
import java.sql.DriverManager;
public class DriverCheck {
public static void main(String[] args) {
long count = DriverManager.drivers().count();
System.out.println("Registered JDBC drivers: " + count);
DriverManager.drivers().forEach(driver ->
System.out.println(" - " + driver.getClass().getName()
+ " (version " + driver.getMajorVersion() + "." + driver.getMinorVersion() + ")"));
}
}
Output with only the H2 JAR on the classpath:
Registered JDBC drivers: 1
- org.h2.Driver (version 2.4)
Output with no driver on the classpath:
Registered JDBC drivers: 0
How it works:
DriverManager.drivers()(Java 9+) returns aStream<Driver>of all registered drivers.getMajorVersion()andgetMinorVersion()report the driver's version, which helps when you are not sure which JAR the build picked.- A count of
0means the driver JAR is missing from the classpath. Fix the build file or-cpoption before looking anywhere else.
Checking for a Driver Class with Class.forName()
You no longer need Class.forName() to register a driver. It is still useful as a quick check that gives a clear message when a specific driver is missing.
public class RequireDriver {
static boolean isOnClasspath(String driverClass) {
try {
Class.forName(driverClass);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
public static void main(String[] args) {
String[] drivers = {"org.h2.Driver", "com.mysql.cj.jdbc.Driver", "org.postgresql.Driver"};
for (String driverClass : drivers) {
String status = isOnClasspath(driverClass) ? "found" : "MISSING";
System.out.printf("%-28s %s%n", driverClass, status);
}
}
}
Output with only the H2 JAR on the classpath:
org.h2.Driver found
com.mysql.cj.jdbc.Driver MISSING
org.postgresql.Driver MISSING
How it works:
Class.forName()loads a class by its full name and throwsClassNotFoundExceptionif it is not on the classpath.- The helper turns that exception into a simple
trueorfalse. %-28spads the class name to 28 characters so the status column lines up.
Prepare a MySQL Database for JDBC
H2 creates its database automatically. A server database such as MySQL needs a database and a user first. The quickest way to get a MySQL server for development is Docker:
docker run --name shop-mysql -d -p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=rootpass \
-e MYSQL_DATABASE=shop \
-e MYSQL_USER=shop_app \
-e MYSQL_PASSWORD=shop_pass \
mysql:8.4
If you installed MySQL yourself, create the same database and user with SQL as the root user:
CREATE DATABASE shop;
CREATE USER 'shop_app'@'localhost' IDENTIFIED BY 'shop_pass';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE ON shop.* TO 'shop_app'@'localhost';
How it works:
- The Docker command starts MySQL 8.4 in the background, publishes port 3306 and creates the
shopdatabase and theshop_appuser on first start. - The SQL version does the same by hand.
GRANTgives the application only the permissions it needs, not fullrootaccess. - Your JDBC URL is then
jdbc:mysql://localhost:3306/shop, with usershop_appand passwordshop_pass.
Note: Never connect your application as
root. A dedicated user with limited rights reduces the damage if the password leaks or the code has a bug.
Keep JDBC Connection Settings Out of the Code
Hard-coding URLs and passwords in Java files means rebuilding to change them and risks committing secrets to Git. A common pattern is a db.properties file plus environment variables that override it.
db.properties:
db.url=jdbc:h2:mem:shop
db.user=sa
db.password=
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
public class DbConfig {
final String url;
final String user;
final String password;
DbConfig(Properties file) {
// An environment variable wins over the file value
this.url = valueOf("DB_URL", file.getProperty("db.url"));
this.user = valueOf("DB_USER", file.getProperty("db.user"));
this.password = valueOf("DB_PASSWORD", file.getProperty("db.password", ""));
}
static String valueOf(String envName, String fileValue) {
String fromEnv = System.getenv(envName);
return (fromEnv != null && !fromEnv.isBlank()) ? fromEnv : fileValue;
}
String masked() {
return "url=" + url + ", user=" + user + ", password=" + (password.isEmpty() ? "(empty)" : "****");
}
public static void main(String[] args) throws IOException {
Properties file = new Properties();
// In a real project: file.load(Files.newBufferedReader(Path.of("db.properties")))
file.load(new StringReader("db.url=jdbc:h2:mem:shop\ndb.user=sa\ndb.password=\n"));
DbConfig config = new DbConfig(file);
System.out.println(config.masked());
}
}
Output (with no DB_* environment variables set):
url=jdbc:h2:mem:shop, user=sa, password=(empty)
How it works:
Properties.load()readskey=valuelines. Here aStringReaderstands in for the file so the example runs anywhere.valueOf()checks an environment variable first, so a server can setDB_URL=jdbc:mysql://...andDB_PASSWORD=...without editing the file.masked()prints the settings without revealing the password, which is safe for logs.
Note: Add files that hold real passwords, such as
db-prod.properties, to.gitignore.
JDBC in a Modular Project
If your project has a module-info.java, it must declare that it uses the java.sql module:
module com.gocourse.shop {
requires java.sql;
}
Without this line, compilation fails with "package java.sql is not visible". The driver JAR itself can stay on the classpath.
Real-World Example: A JDBC Setup Checker
When a project will not connect, you want to know which step fails. This tool checks the driver, opens a connection, runs a test query and prints a checklist. Run it whenever you set up a new machine or server.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcSetupChecker {
record Settings(String url, String user, String password, String driverClass) {}
static void pass(String step, String detail) {
System.out.printf("[PASS] %-18s %s%n", step, detail);
}
static void fail(String step, String detail) {
System.out.printf("[FAIL] %-18s %s%n", step, detail);
}
static boolean checkDriver(Settings settings) {
try {
Class.forName(settings.driverClass());
pass("Driver on classpath", settings.driverClass());
return true;
} catch (ClassNotFoundException e) {
fail("Driver on classpath", settings.driverClass() + " not found: add the driver JAR");
return false;
}
}
static boolean checkConnection(Settings settings) {
try (Connection connection = DriverManager.getConnection(settings.url(), settings.user(), settings.password())) {
DatabaseMetaData meta = connection.getMetaData();
pass("Connection", meta.getDatabaseProductName() + " " + meta.getDatabaseMajorVersion()
+ "." + meta.getDatabaseMinorVersion());
try (Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT 1")) {
rows.next();
pass("Test query", "SELECT 1 returned " + rows.getInt(1));
}
pass("Connection valid", String.valueOf(connection.isValid(2)));
return true;
} catch (SQLException e) {
fail("Connection", "SQLState " + e.getSQLState() + ": " + e.getMessage());
return false;
}
}
public static void main(String[] args) {
Settings settings = new Settings(
System.getenv().getOrDefault("DB_URL", "jdbc:h2:mem:setupcheck"),
System.getenv().getOrDefault("DB_USER", "sa"),
System.getenv().getOrDefault("DB_PASSWORD", ""),
System.getenv().getOrDefault("DB_DRIVER", "org.h2.Driver"));
System.out.println("Checking " + settings.url());
boolean ok = checkDriver(settings) && checkConnection(settings);
System.out.println(ok ? "JDBC setup is ready." : "Fix the first FAIL line and run again.");
}
}
Output with the H2 JAR on the classpath:
Checking jdbc:h2:mem:setupcheck
[PASS] Driver on classpath org.h2.Driver
[PASS] Connection H2 2.4
[PASS] Test query SELECT 1 returned 1
[PASS] Connection valid true
JDBC setup is ready.
Output without any driver JAR:
Checking jdbc:h2:mem:setupcheck
[FAIL] Driver on classpath org.h2.Driver not found: add the driver JAR
Fix the first FAIL line and run again.
How it works:
- Settings from the environment. A
Settingsrecord holds the URL, user, password and driver class. Each value comes from an environment variable with an H2 default, so the same tool can check MySQL withDB_URL=jdbc:mysql://localhost:3306/shop DB_DRIVER=com.mysql.cj.jdbc.Driver. - Step 1: the driver.
checkDriver()usesClass.forName()to confirm the JAR is present and gives a direct hint if it is not. - Step 2: the connection.
checkConnection()opens a connection and prints the database name and version fromDatabaseMetaData. - Step 3: a real query.
SELECT 1proves that SQL can travel to the database and back. - Step 4: validity.
isValid(2)asks the driver to confirm the connection is alive, waiting at most 2 seconds. - Stop at the first failure. The
&&operator runscheckConnection()only ifcheckDriver()succeeded, so the report always points at the first real problem.
With the setup working, the next lesson, Java Database Connection, explains connection URLs, properties and timeouts in detail. For an overview of how the pieces fit together, see Java JDBC Basics.