Java JDBC Setup

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 212 of 306

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

RequirementWhyHow to check
JDK 17 or newerCompiles and runs your code; contains java.sqljava -version
A JDBC driver JARTranslates JDBC calls for one databaseListed in your build file or classpath
A databaseStores the dataH2 needs nothing; MySQL/PostgreSQL need a running server
Connection detailsURL, user name, passwordFrom 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, Statement and ResultSet are 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.

DatabaseMaven coordinates (groupId:artifactId)Driver classURL prefix
H2com.h2database:h2org.h2.Driverjdbc:h2:
MySQLcom.mysql:mysql-connector-jcom.mysql.cj.jdbc.Driverjdbc:mysql:
PostgreSQLorg.postgresql:postgresqlorg.postgresql.Driverjdbc:postgresql:
SQLiteorg.xerial:sqlite-jdbcorg.sqlite.JDBCjdbc:sqlite:
SQL Servercom.microsoft.sqlserver:mssql-jdbccom.microsoft.sqlserver.jdbc.SQLServerDriverjdbc:sqlserver:

Note: The old MySQL artifact mysql:mysql-connector-java and the driver class com.mysql.jdbc.Driver are outdated. Use com.mysql:mysql-connector-j and com.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.release sets the Java version your code is compiled for.
  • Run mvn compile and 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.sql interfaces, 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.
  • implementation makes H2 available at compile time and run time, which you need if you use H2 classes directly (such as its DataSource).
  • runtimeOnly adds the MySQL driver only when the program runs, because your code talks to it only through java.sql interfaces.
  • gradle run downloads the drivers, compiles and starts DriverCheck.

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 .class files 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 get No 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 a Stream<Driver> of all registered drivers.
  • getMajorVersion() and getMinorVersion() report the driver's version, which helps when you are not sure which JAR the build picked.
  • A count of 0 means the driver JAR is missing from the classpath. Fix the build file or -cp option 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 throws ClassNotFoundException if it is not on the classpath.
  • The helper turns that exception into a simple true or false.
  • %-28s pads 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 shop database and the shop_app user on first start.
  • The SQL version does the same by hand. GRANT gives the application only the permissions it needs, not full root access.
  • Your JDBC URL is then jdbc:mysql://localhost:3306/shop, with user shop_app and password shop_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() reads key=value lines. Here a StringReader stands in for the file so the example runs anywhere.
  • valueOf() checks an environment variable first, so a server can set DB_URL=jdbc:mysql://... and DB_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:

  1. Settings from the environment. A Settings record 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 with DB_URL=jdbc:mysql://localhost:3306/shop DB_DRIVER=com.mysql.cj.jdbc.Driver.
  2. Step 1: the driver. checkDriver() uses Class.forName() to confirm the JAR is present and gives a direct hint if it is not.
  3. Step 2: the connection. checkConnection() opens a connection and prints the database name and version from DatabaseMetaData.
  4. Step 3: a real query. SELECT 1 proves that SQL can travel to the database and back.
  5. Step 4: validity. isValid(2) asks the driver to confirm the connection is alive, waiting at most 2 seconds.
  6. Stop at the first failure. The && operator runs checkConnection() only if checkDriver() 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java JDBC Setup and get answers drawn from it.

Signed-in readers only.