Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

DriverManager.getConnection()

Opens a connection to a database by its JDBC URL.

Available since: Java 1.1

Syntax

public static Connection getConnection(String url, String user, String password) throws SQLException

Parameters

ParameterTypeDescription
urlStringThe database URL, like jdbc:postgresql://host:5432/db or jdbc:sqlite:shop.db.
userStringThe user name (optional — there is a url-only variant).
passwordStringThe password.

Return value

ConnectionAn open connection that must be closed.

Examples

A connection to an in-memory SQLite database. The examples run with the driver on the class path: java --enable-native-access=ALL-UNNAMED -cp sqlite-jdbc-3.53.4.0.jar Main.java:

import java.sql.*;
 
void main() throws SQLException {
    try (Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:")) {
        IO.println(conn.getMetaData().getDatabaseProductName());
        IO.println(conn.isClosed());
    }
}

Output:

SQLite
false

Creating a table and running simple queries with a Statement:

import java.sql.*;
 
void main() throws SQLException {
    try (Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:");
         Statement st = conn.createStatement()) {
        st.executeUpdate("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
        int added = st.executeUpdate("INSERT INTO users (name) VALUES ('Anna'), ('Oleg')");
        IO.println("Added: " + added);
 
        try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM users")) {
            rs.next();
            IO.println("Total: " + rs.getInt(1));
        }
    }
}

Output:

Added: 2
Total: 2

If the driver for the database is not on the class path:

import java.sql.*;
 
void main() throws SQLException {
    DriverManager.getConnection("jdbc:postgresql://localhost:5432/shop", "app", "secret");
}

Output:

Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/shop

Notes

JDBC lives in the java.sql module, so you need import java.sql.*;. The driver for a specific database is a separate library: org.postgresql:postgresql, com.mysql:mysql-connector-j, org.xerial:sqlite-jdbc; it registers itself as soon as it is on the class path. A connection is an expensive resource: close it with try with resources, and in web applications take connections from a pool (HikariCP). Passwords are not written in code — read them from an environment variable.

See also

  • PreparedStatement — A precompiled SQL query with ? parameters. Protects against SQL injection.
  • ResultSet — The result of a SELECT query: a cursor that walks through the rows one by one.
  • Connection.setAutoCommit() — Turns auto-commit on or off. With false several queries form a transaction: commit() or rollback().
  • try-with-resources — A `try` block that closes opened resources automatically — files, connections, streams.

Related recipes

In the tutorial

  • JDBC basics — Working with a database from Java through JDBC — what a driver is, connecting with DriverManager.getConnection, Statement for SQL commands and reading rows with ResultSet, using SQLite.

Thanks for reading!

Donate to the site — we work hard for you.