To connect to a PostgreSQL database using JDBC, you’ll need the PostgreSQL JDBC driver and a properly formatted connection URL.
1. Add the Dependency
Add the following dependency to your pom.xml file:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.4</version>
</dependency>
2. Establish the Connection
In modern JDBC (4.0+), you no longer need to manually call Class.forName(). The DriverManager will automatically find the driver on your classpath.
Here is a standard example using a try-with-resources block to ensure the connection is closed automatically:
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PostgresConnectionExample {
public static void main(String[] args) {
// URL format: jdbc:postgresql://<host>:<port>/<database>
String url = "jdbc:postgresql://localhost:5432/your_database";
String user = "your_username";
String password = "your_password";
try (Connection connection = DriverManager.getConnection(url, user, password)) {
if (connection != null) {
System.out.println("Connected to the PostgreSQL server successfully!");
}
} catch (SQLException e) {
System.err.println("Connection failure: " + e.getMessage());
}
}
}
Key Details:
- JDBC URL: The prefix is always
jdbc:postgresql://. The default port for PostgreSQL is5432. - Driver Class: If you are working with older code that requires it, the driver class name is
org.postgresql.Driver.
