Careeroza
Connecting with DriverManager
JDBC in One Picture
JDBC (Java Database Connectivity, package java.sql) is the low-level API every Java database library — including Hibernate — uses underneath. A vendor driver jar (MySQL Connector/J, PostgreSQL JDBC) implements it.
Java code -> java.sql API (Connection, PreparedStatement, ResultSet)
-> JDBC driver jar (com.mysql:mysql-connector-j)
-> network -> MySQL serverOpening a Connection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcDemo {
private static final String URL = "jdbc:mysql://localhost:3306/shopease";
private static final String USER = "shopease";
private static final String PASSWORD = "secret";
public static void main(String[] args) throws SQLException {
// try-with-resources closes the connection automatically
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
System.out.println("Connected to " + conn.getMetaData().getDatabaseProductName());
}
}
}| Database | JDBC URL | Maven driver |
|---|---|---|
| MySQL | jdbc:mysql://localhost:3306/shopease | com.mysql:mysql-connector-j |
| PostgreSQL | jdbc:postgresql://localhost:5432/shopease | org.postgresql:postgresql |
| H2 (in-memory) | jdbc:h2:mem:shopease | com.h2database:h2 |
Note: Opening a real connection takes tens of milliseconds. Production apps never call DriverManager per request; they use a connection pool (HikariCP, the Spring Boot default) that keeps connections open and lends them out.