Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource
Get a database to practice with, write JDBC URLs for PostgreSQL, MySQL, Oracle, SQL Server, H2 and SQLite, put the driver JAR on the class path, connect with DriverManager or a DataSource, keep credentials out of code, trace JDBC calls and handle login failures.
kvi5hnuCode Sprout team member10 min readOn this page
Before you can run a single SQL statement from Java, you need three things: a running database, the JDBC driver for it, and the connection details (URL, user name and password). This article covers each of them and then shows the two ways to obtain a Connection: DriverManager and DataSource.
Getting a database to practice with
Any database with a JDBC driver works. Here are three easy options:
-
An embedded database. H2, HSQLDB and SQLite run inside your program, so there's nothing to install apart from the driver JAR. The URL
jdbc:h2:mem:shopcreates a throwaway in-memory database. That's ideal for learning and for unit tests, though each embedded database has its own SQL quirks. -
A server in a container. With Docker or Podman, a real PostgreSQL server is one command away:
textdocker run --name shopdb -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=shop -p 5432:5432 -d postgres:18Tests can start such containers automatically with the Testcontainers library.
-
A locally installed server such as PostgreSQL, MySQL or MariaDB, or a cloud database. In that case, ask an administrator for an account that may create and drop tables.
Apache Derby, which earlier JDK versions shipped as "Java DB", was retired by its developers in October 2025 and gets no more fixes, so don't start new projects with it.
Each database comes with an interactive SQL tool (psql, mysql, sqlite3, H2's Shell and web console). Use it to try statements before putting them into Java code.
Database URLs
A JDBC URL has the form jdbc:<subprotocol>:<details>. The subprotocol selects the driver, and the rest is in a vendor-specific format. Look it up in your driver's documentation:
| Database | Example URL |
|---|---|
| PostgreSQL | jdbc:postgresql://localhost:5432/shop |
| MySQL | jdbc:mysql://localhost:3306/shop |
| MariaDB | jdbc:mariadb://localhost:3306/shop |
| Oracle | jdbc:oracle:thin:@//localhost:1521/FREEPDB1 |
| SQL Server | jdbc:sqlserver://localhost:1433;databaseName=shop;encrypt=true |
| H2, in memory | jdbc:h2:mem:shop (add ;DB_CLOSE_DELAY=-1 to keep it alive between connections) |
| H2, in a file | jdbc:h2:file:./data/shop or jdbc:h2:./data/shop |
| SQLite | jdbc:sqlite:shop.db |
Many drivers accept settings in the URL, such as ?sslmode=require or ?connectTimeout=5, or as connection properties (see below).
The driver JAR
The driver is a library like any other. With Maven or Gradle you add it as a runtime dependency, for example org.postgresql:postgresql, com.mysql:mysql-connector-j or com.h2database:h2. Your code compiles against the java.sql interfaces only, so the driver isn't needed for compiling. It must be present when the program runs:
java -cp .:lib/postgresql.jar app.Main (use ; instead of : on Windows)
On the module path, drivers are usually automatic modules, and your own module needs requires java.sql;.
How the driver is found
Since JDBC 4.0 (Java 6), every driver JAR contains a file META-INF/services/java.sql.Driver that names its driver class. The first time you ask DriverManager for a connection, it uses the ServiceLoader (Core Java I's service loader article) to load all such drivers. Each driver class registers itself with DriverManager.registerDriver in a static initializer. When you call getConnection(url, ...), DriverManager offers the URL to each registered driver in turn. A driver returns null from connect for URLs it doesn't understand, and the first one that accepts the URL opens the connection.
So you don't need the old Class.forName("org.postgresql.Driver") line any more. For an ancient driver without the services file, you can name the class in the jdbc.drivers system property (java -Djdbc.drivers=com.example.OldDriver ...), separating several class names with colons.
Connecting with DriverManager
String url = "jdbc:postgresql://localhost:5432/shop";
try (Connection conn = DriverManager.getConnection(url, "shopuser", password)) {
// use the connection
}
A Connection represents one session with the database. Opening one is slow, because it involves a network round trip, authentication and session setup, and each holds resources on the server. Always close connections, which try-with-resources does for you. Server applications borrow connections from a pool instead of opening new ones (article 66).
Further settings go in a Properties object. user and password are standard, and anything else is driver-specific:
var info = new Properties();
info.setProperty("user", "shopuser");
info.setProperty("password", password);
info.setProperty("ssl", "true"); // PostgreSQL driver property
info.setProperty("ApplicationName", "inventory"); // shows up in the server's session list
Connection conn = DriverManager.getConnection(url, info);
DriverManager.setLoginTimeout(seconds) limits how long drivers wait while connecting. Once you're connected, conn.isValid(seconds) checks that the connection still works. conn.setNetworkTimeout(executor, millis) limits how long any single call waits for the server.
A first complete program
This program reads the connection settings from database.properties, takes the password from the environment variable DB_PASSWORD if it is set, connects, prints some information about the database, and creates, fills, reads and drops a table. With the settings below, it runs against an in-memory H2 database when the H2 JAR is on the class path. To use a different database, change the properties file.
jdbc.url=jdbc:h2:mem:shop
jdbc.username=sa
jdbc.password=
import java.io.*;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
public class TestDb {
public static void main(String[] args) throws IOException {
try (Connection conn = getConnection()) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("Connected to " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
System.out.println("Driver " + meta.getDriverName() + " " + meta.getDriverVersion()
+ ", JDBC " + meta.getJDBCMajorVersion() + "." + meta.getJDBCMinorVersion());
try (Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE greetings (message VARCHAR(20))");
stat.executeUpdate("INSERT INTO greetings VALUES ('Hello, World!')");
try (ResultSet rs = stat.executeQuery("SELECT * FROM greetings")) {
while (rs.next()) System.out.println(rs.getString(1));
}
stat.executeUpdate("DROP TABLE greetings");
}
} catch (SQLException e) {
for (Throwable t : e) System.err.println(t);
}
}
static Connection getConnection() throws IOException, SQLException {
var props = new Properties();
try (Reader in = Files.newBufferedReader(Path.of("database.properties"))) {
props.load(in);
}
String url = props.getProperty("jdbc.url");
String user = props.getProperty("jdbc.username");
String password = Objects.requireNonNullElse(System.getenv("DB_PASSWORD"), props.getProperty("jdbc.password"));
return DriverManager.getConnection(url, user, password);
}
}
Output with java -cp h2-2.3.232.jar:. TestDb:
Connected to H2 2.3.232 (2024-08-11)
Driver H2 JDBC Driver 2.3.232 (2024-08-11), JDBC 4.3
Hello, World!
Iterating over the SQLException in the catch clause visits all chained exceptions and their causes, as article 59 explains.
Tracing
When a connection doesn't work, DriverManager.setLogWriter(new PrintWriter(System.out, true)) makes DriverManager report what it does, such as which drivers it loaded and which it tried for a URL. With H2, it looks like this:
DriverManager.getConnection("jdbc:h2:mem:other")
trying org.h2.Driver
getConnection returning org.h2.Driver
Drivers have their own, much more detailed logging, usually through java.util.logging loggers named after the driver's packages (such as org.postgresql) or a URL setting (such as TRACE_LEVEL_SYSTEM_OUT=2 for H2). Check your driver's documentation.
Login failures
A wrong user name or password raises an SQLException whose SQLState starts with 28, usually 28000 or, with PostgreSQL, 28P01. Drivers that use the standard SQLException subclasses report this as SQLInvalidAuthorizationSpecException, but some, including the PostgreSQL driver, throw their own plain SQLException subclass for every error. Checking getSQLState() works everywhere. Network problems, such as a database that isn't running, give SQLState class 08 (and, with drivers that use the subclasses, SQLNonTransientConnectionException or SQLTransientConnectionException). Unlike authentication failures, a transient connection failure may succeed when retried.
DataSource: the preferred way
DriverManager couples your code to a URL and credentials. The interface javax.sql.DataSource hides them. The code that needs connections receives a DataSource and just calls getConnection(). Where the connections come from (a single database, a connection pool, or a test database) is decided by whoever configures the data source:
var ds = new org.h2.jdbcx.JdbcDataSource(); // or PGSimpleDataSource, a HikariDataSource, ...
ds.setURL("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1");
ds.setUser("sa");
ds.setPassword(password);
DataSource dataSource = ds; // pass this to the rest of the application
try (Connection conn = dataSource.getConnection()) { ... }
Each driver ships with its own DataSource classes, configured through JavaBeans setters. Pool libraries like HikariCP, application servers and frameworks like Spring Boot create a pooled DataSource from configuration and inject it into your code. In application servers it's looked up by name through JNDI (article 66). Prefer DataSource in everything except throwaway programs.
JDBC 4.3 (Java 9) added DataSource.createConnectionBuilder(), which builds a connection with a different user (or a sharding key for sharded databases): ds.createConnectionBuilder().user("report").password(pw).build(). Support is optional. The default implementation throws SQLFeatureNotSupportedException, and H2's data source, for example, doesn't support it.
Most JDBC interfaces extend Wrapper. unwrap(VendorInterface.class) gives access to driver-specific features behind a pool's or framework's proxy objects, and isWrapperFor checks first.
The program
The demo again uses a toy driver, because the runnable examples can't include a real one. This time the driver registers itself in a static initializer, just like a real driver. It is loaded through the jdbc.drivers property, which is set before DriverManager first looks for drivers. The connection settings come from a properties file, and the password can be overridden by an environment variable. With a log writer installed, DriverManager traces how it loads the driver and finds it for the URL. The demo then passes extra properties, triggers a login failure, and gets connections from a DataSource, including through a ConnectionBuilder and unwrap.
import java.io.*;
import java.lang.reflect.Proxy;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Logger;
import javax.sql.DataSource;
public class Solution {
// A toy driver standing in for a vendor driver. Like real drivers, it registers itself
// in a static initializer, so loading the class is enough.
public static class ToyDriver implements Driver {
static {
try { DriverManager.registerDriver(new ToyDriver()); }
catch (SQLException e) { throw new ExceptionInInitializerError(e); }
}
@Override public boolean acceptsURL(String url) { return url.startsWith("jdbc:toy:"); }
@Override public Connection connect(String url, Properties info) throws SQLException {
if (!acceptsURL(url)) return null;
if (!"secret".equals(info.getProperty("password")))
throw new SQLInvalidAuthorizationSpecException("password check failed for " + info.getProperty("user"), "28000");
String db = url.substring("jdbc:toy:".length());
var props = new TreeMap<>(info);
props.remove("password"); // don't echo secrets
return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[] { Connection.class },
(proxy, method, args) -> switch (method.getName()) {
case "getCatalog" -> db;
case "isValid" -> true;
case "close" -> null;
case "toString" -> "ToyConnection[" + db + ", " + props + "]";
default -> throw new SQLFeatureNotSupportedException(method.getName());
});
}
@Override public String toString() { return "ToyDriver"; }
@Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { return new DriverPropertyInfo[0]; }
@Override public int getMajorVersion() { return 1; }
@Override public int getMinorVersion() { return 0; }
@Override public boolean jdbcCompliant() { return false; }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); }
}
// A minimal DataSource: configured with setters, hands out connections, supports ConnectionBuilder
public static class ToyDataSource implements DataSource {
private String url, user, password;
private PrintWriter logWriter;
private int loginTimeout;
public void setURL(String url) { this.url = url; }
public void setUser(String user) { this.user = user; }
public void setPassword(String password) { this.password = password; }
@Override public Connection getConnection() throws SQLException { return getConnection(user, password); }
@Override public Connection getConnection(String user, String password) throws SQLException {
var info = new Properties();
info.setProperty("user", user);
info.setProperty("password", password);
return new ToyDriver().connect(url, info);
}
@Override public ConnectionBuilder createConnectionBuilder() {
return new ConnectionBuilder() {
private String u = user, p = password;
@Override public ConnectionBuilder user(String username) { u = username; return this; }
@Override public ConnectionBuilder password(String pw) { p = pw; return this; }
@Override public ConnectionBuilder shardingKey(ShardingKey key) { return this; }
@Override public ConnectionBuilder superShardingKey(ShardingKey key) { return this; }
@Override public Connection build() throws SQLException { return getConnection(u, p); }
};
}
@Override public PrintWriter getLogWriter() { return logWriter; }
@Override public void setLogWriter(PrintWriter out) { logWriter = out; }
@Override public void setLoginTimeout(int seconds) { loginTimeout = seconds; }
@Override public int getLoginTimeout() { return loginTimeout; }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); }
@Override public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) return iface.cast(this);
throw new SQLException("not a wrapper for " + iface.getName());
}
@Override public boolean isWrapperFor(Class<?> iface) { return iface.isInstance(this); }
}
public static void main(String[] args) throws Exception {
// 1. Connection settings come from a file (and secrets from the environment), not from the code
Path config = Files.createTempFile("database", ".properties");
Files.writeString(config, """
# connection settings
jdbc.url=jdbc:toy:shop
jdbc.username=ada
jdbc.password=secret
""");
var props = new Properties();
try (Reader in = Files.newBufferedReader(config)) { props.load(in); }
Files.delete(config);
String password = Objects.requireNonNullElse(System.getenv("TOY_DB_PASSWORD"), props.getProperty("jdbc.password"));
// 2. The jdbc.drivers property names driver classes for DriverManager to load (for old drivers
// without a META-INF/services entry). It is read when DriverManager first looks for drivers.
System.setProperty("jdbc.drivers", "Solution$ToyDriver");
DriverManager.setLogWriter(new PrintWriter(System.out, true)); // JDBC tracing
DriverManager.setLoginTimeout(5);
try (Connection conn = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.username"), password)) {
System.out.println("=> " + conn + ", catalog " + conn.getCatalog() + ", valid " + conn.isValid(2));
}
DriverManager.setLogWriter(null);
// 3. Extra driver properties go in a Properties object
var info = new Properties();
info.setProperty("user", "ada");
info.setProperty("password", password);
info.setProperty("ssl", "true");
info.setProperty("ApplicationName", "inventory");
try (Connection conn = DriverManager.getConnection("jdbc:toy:shop", info)) {
System.out.println("properties seen by the driver: " + conn);
}
// 4. A wrong password is reported with SQLState class 28
try {
DriverManager.getConnection("jdbc:toy:shop", "ada", "guess");
} catch (SQLInvalidAuthorizationSpecException e) {
System.out.println(e.getClass().getSimpleName() + " [" + e.getSQLState() + "]: " + e.getMessage());
}
// 5. A DataSource is configured once and handed to the code that needs connections
var ds = new ToyDataSource();
ds.setURL("jdbc:toy:warehouse");
ds.setUser("app");
ds.setPassword("secret");
DataSource dataSource = ds; // application code sees only the interface
try (Connection conn = dataSource.getConnection()) {
System.out.println("from DataSource: " + conn);
}
try (Connection conn = dataSource.createConnectionBuilder().user("report").password("secret").build()) {
System.out.println("from ConnectionBuilder: " + conn);
}
System.out.println("unwrap: " + dataSource.unwrap(ToyDataSource.class).getClass().getSimpleName());
}
}
DriverManager.getConnection("jdbc:toy:shop")
DriverManager.initialize: jdbc.drivers = Solution$ToyDriver
number of Drivers:1
DriverManager.Initialize: loading Solution$ToyDriver
registerDriver: ToyDriver
JDBC DriverManager initialized
trying Solution$ToyDriver
getConnection returning Solution$ToyDriver
=> ToyConnection[shop, {user=ada}], catalog shop, valid true
properties seen by the driver: ToyConnection[shop, {ApplicationName=inventory, ssl=true, user=ada}]
SQLInvalidAuthorizationSpecException [28000]: password check failed for ada
from DataSource: ToyConnection[warehouse, {user=app}]
from ConnectionBuilder: ToyConnection[warehouse, {user=report}]
unwrap: ToyDataSource
Common questions
Why do I get "No suitable driver found for jdbc:..."?
Either the driver JAR isn't on the runtime class path, or the URL is misspelled so no driver accepts it (for example jdbc:postgres: instead of jdbc:postgresql:). Check the JAR with -verbose:class or by listing the class path, and compare the URL with the driver documentation.
Do I still need Class.forName("...Driver")?
No, not for any driver from the last 15 years. One exception is environments where the driver is invisible to DriverManager's class loader, such as some application server or plugin setups; there, loading it explicitly or using a DataSource helps.
Where should the database password come from? An environment variable, a secrets manager (Vault, AWS Secrets Manager, Kubernetes secrets mounted as files), or the application server's configuration. Not from source code, and not from a properties file in version control.
How do I connect to a database with SSL/TLS?
With a driver-specific URL setting, for example sslmode=verify-full for PostgreSQL or sslMode=VERIFY_IDENTITY for MySQL, plus a trust store containing the server's CA certificate if it isn't publicly signed. Use the verifying modes; require without verification encrypts but doesn't authenticate the server.
How many connections should my application open? Few, and reused through a pool (article 66). Databases handle a limited number of connections well, often a few dozen to a few hundred. A pool of 10 to 20 connections serves many requests per second when each transaction is short.
API reference
| API | Purpose |
|---|---|
DriverManager.getConnection(url), (url, user, password), (url, properties) | open a connection |
DriverManager.setLoginTimeout, setLogWriter, drivers(), registerDriver | configuration and tracing |
jdbc.drivers system property, META-INF/services/java.sql.Driver | how drivers are found |
javax.sql.DataSource.getConnection(), getConnection(user, password) | obtain connections from a configured source |
DataSource.createConnectionBuilder(), ConnectionBuilder.user, password, build | build a connection with options (JDBC 4.3, optional) |
Connection.isValid(seconds), setNetworkTimeout, getCatalog, getSchema, setSchema, close | connection state and settings |
Connection.getMetaData(), DatabaseMetaData.getDatabaseProductName, getDriverVersion | what you are connected to (article 64) |
Wrapper.unwrap(iface), isWrapperFor(iface) | reach vendor-specific interfaces |
SQLInvalidAuthorizationSpecException, SQLNonTransientConnectionException, SQLTransientConnectionException | login and connection failures |
Summary
- You need a database, its driver JAR at run time, and a JDBC URL in the vendor's format
jdbc:<subprotocol>:<details>. - Drivers register themselves through
META-INF/services/java.sql.Driver. NoClass.forNameis needed.DriverManagerpicks the first driver that accepts the URL. - Open connections with try-with-resources, set login and network timeouts, and keep credentials out of source code.
- Prefer a
DataSource, usually a pooled one supplied by configuration, overDriverManagerin real applications. - Use
setLogWriterand driver logging to troubleshoot. Login failures have SQLState class 28, connection failures class 08.
Practice Questions
Your program compiles but fails at run time with "No suitable driver found for jdbc:mysql://...". The code doesn't mention any MySQL class. What's missing?
The MySQL driver JAR (com.mysql:mysql-connector-j) on the run-time class path. Compiling only needs the java.sql interfaces, but at run time DriverManager must find a driver that accepts the jdbc:mysql: URL, and drivers are discovered from the JARs on the class path.
Why is Class.forName("com.mysql.cj.jdbc.Driver") unnecessary in modern code, and when would you still need something like it?
Since JDBC 4.0, driver JARs declare their driver class in META-INF/services/java.sql.Driver, and DriverManager loads them automatically through the ServiceLoader. You'd need explicit loading only for a very old driver without that file, or when the driver is in a class loader DriverManager doesn't search. The jdbc.drivers system property is an alternative for the first case.
Why should library and application code ask for a DataSource rather than call DriverManager.getConnection?
A DataSource hides the URL, credentials and connection strategy. Configuration decides whether connections come from a pool, which database they go to, and how they're secured, so the same code works in production, in tests and in an application server. Pooled data sources also make connecting cheap, while DriverManager opens a new physical connection every time.
How can you tell a wrong password from a database server that isn't reachable when getConnection throws?
Look at the SQLState or the exception subclass. Authentication failures have SQLState class 28 (SQLInvalidAuthorizationSpecException), and retrying won't help. Connection problems have class 08, sometimes as SQLTransientConnectionException, where a retry later may succeed.
You use jdbc:h2:mem:shop and create a table with one connection. A second connection opened later doesn't see the table. Why?
By default, an in-memory H2 database exists only while at least one connection to it is open. When the first connection closed, the database was discarded, and the second connection created a new, empty one. Keep a connection open, or add ;DB_CLOSE_DELAY=-1 to the URL to keep the database for the life of the JVM.
Previous: JDBC Design and SQL Basics: How Java Talks to Databases
Next: Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
Related reading
- JDBC Design and SQL Basics: How Java Talks to Databases
- Sending Email from Java: SMTP and Jakarta Mail
- A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters
- Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
- The Java HttpClient: Requests, Responses, Body Publishers and Handlers

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.