Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To connect a Java application to a database, add that database’s JDBC driver, build a vendor-specific JDBC URL, provide credentials, and open a Connection. For a small standalone example, DriverManager.getConnection(...) makes the process visible. In a configured application, Java SE documentation identifies DataSource as the preferred connection mechanism.

What JDBC does

JDBC is Java’s API for working with data sources, especially relational databases. A JDBC driver translates between the API and a particular database. Once connected, an application can send SQL statements and process results; opening the connection is the first step, not the whole JDBC workflow. See Oracle’s JDBC introduction.

What you need before connecting

  • A database and its connection details. You need the database host or local location, port where applicable, database name, and the required authentication details.
  • The matching JDBC driver. Add the driver dependency to your project or otherwise make it available to the application. The driver is software; it is not a physical accessory.
  • The vendor’s JDBC URL format. URLs are not interchangeable between databases. The URL identifies a driver subprotocol and database location or name, and may include optional configuration.

Oracle’s older tutorial gives jdbc:mysql://localhost:3306/ and jdbc:derby:testdb;create=true as examples. They illustrate that formats differ; neither is a universal JDBC URL. Use the documentation for the database and driver version you chose.

Build a JDBC connection in order

1. Make the driver available

Install or declare the JDBC driver using the method appropriate to your project and the driver’s current installation instructions. Oracle’s tutorial explains that JDBC 4.0 drivers found on the class path are loaded automatically; older pre-4.0 drivers may require explicit loading. Follow the chosen driver’s instructions rather than adding an old driver-loading line by habit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, the current MySQL Connector/J guide identifies com.mysql.cj.jdbc.Driver. That is a MySQL-specific class name, not a name to use for other databases. Consult the MySQL Connector/J guide for its installation and version guidance.

2. Get the database’s URL

Ask the database vendor’s documentation for the exact URL syntax and supported options. Do not transplant a MySQL URL, SQL Server authentication property, Oracle example, or TLS option to a different driver.

3. Supply credentials without exposing them

DriverManager accepts credentials as arguments or through a properties object. In an application, obtain secrets using its established secret-management approach; do not commit real passwords to source code or print them in error output. Avoid specifying the same setting in both the URL and a properties object: the Java SE API says precedence in that case is implementation-defined.

4. Open and close the connection

This minimal example uses placeholders, so replace the URL and credential values with configuration for your database. The driver must already be available to the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcConnectionExample {
    public static void main(String[] args) {
        String url = System.getenv("DB_URL");
        String user = System.getenv("DB_USER");
        String password = System.getenv("DB_PASSWORD");

        try (Connection connection = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connected to the database.");
            // Create and execute SQL statements using this connection.
        } catch (SQLException e) {
            System.err.println("Could not connect to the database: " + e.getMessage());
        }
    }
}

The try-with-resources statement closes the connection when the block ends, including when an exception occurs. The example reads credentials from environment variables to avoid hard-coding them; choose a secret-management method that fits your deployment. Do not log the URL if it contains credentials or other secrets.

DriverManager or DataSource?

Oracle’s Java SE 25 API calls DataSource the preferred means of connecting to a data source. Oracle’s Establishing a Connection tutorial explains: “A DataSource interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application.”

Mechanism When it fits What to know
DriverManager A small standalone example or simple program where you want to see the connection flow directly. It selects an appropriate registered driver for the supplied URL. The application passes connection details when it requests a connection.
DataSource An application where connection configuration should be separated from application code, or where a framework or server supplies connection infrastructure. It is an interface; its implementation and environment determine what services it provides. JDBC does not guarantee that every DataSource pools connections.

You do not need to introduce a connection pool just to learn JDBC basics. A DataSource becomes useful when your application’s configuration or managed environment calls for one. Microsoft’s SQL Server JDBC documentation shows both DriverManager and SQLServerDataSource patterns; those are SQL Server examples, not general URL or property syntax. See the Microsoft SQL Server JDBC connection guide.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Diagnose a failed connection

Connection setup can throw SQLException; Java SE also documents login-timeout errors. Check the following in a practical order:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. URL: Confirm the driver’s required prefix, host, port, database name, and option syntax. A URL accepted by one vendor’s driver may be invalid for another.
  2. Driver availability: Verify that the correct driver dependency is present at runtime, not merely in an editor or compile-time setup. Check the vendor’s current guidance about automatic or explicit loading.
  3. Credentials and authentication settings: Check the account, password, and any vendor-specific authentication requirements. Do not include secrets when sharing logs or stack traces.
  4. Database reachability: Confirm that the database is running and reachable from the application host, and that network or firewall rules permit the connection.
  5. Timeout configuration: If a login timeout is configured, determine whether the database or network is responding within it; Java SE documents timeout-related connection failures.

Use the exception details to narrow the issue, but keep secrets out of diagnostic output. If the error concerns a vendor-specific property or URL option, check that driver’s current documentation rather than assuming it is part of JDBC itself.

Version and vendor differences

Oracle’s JDBC tutorial explicitly says its examples were written for JDK 8 and do not use later improvements. It remains useful for the basic concepts, but current implementations should follow the chosen database driver’s documentation and the Java version in use. Driver class names, URL syntax, authentication properties, and TLS options vary by vendor and may change across driver versions.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.