How to Connect to Postgres via JDBC

The official PostgreSQL JDBC driver can be downloaded from the following:

https://jdbc.postgresql.org/download.html

Everything necessary to connect to PostgreSQL over JDBC is provided in the downloaded .jar file.

To connect to PostgreSQL via JDBC, the class name of the driver is required. Listed below is the class name to use with the standard PostgreSQL JDBC driver:

org.postgresql.Driver

In addition to the class name, a JDBC URL needs constructed to connect to a Postgres database. Listed below are examples of JDBC URLs to use with the PostgreSQL JDBC driver.

 

PostgreSQL Driver JDBC URL Formats

Connect to a PostgreSQL database named sample running on the local machine:

jdbc:postgresql://localhost:5432/sample

Connect to a Postgres database named sample running on another machine using SSL encryption:

jdbc:postgresql://192.168.1.170:5432/sample?ssl=true

Connect to a PosgreSQL database named sample running on another machine using SSL encryption with certificate validation turned off:

jdbc:postgresql://192.168.1.170:5432/sample?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory

Sample Code for Making a JDBC Connection

Below is sample Java code for using the PostgreSQL JDBC driver to make a connection to the database.

Class dbDriver = Class.forName("org.postgresql.Driver"); String jdbcURL = "jdbc:postgresql://192.168.1.170:5432/sample?ssl=true"; Connection connection = DriverManager.getConnection(jdbcURL, "user", "password"); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("select * from employee"); while(rs.next()) { System.out.println("name = " + rs.getString("name")); System.out.println("id = " + rs.getInt("id")); } . . .

MySQL: How to Connect to MySQL via JDBC

Microsoft SQL Server: How to Connect to MS SQL Server via JDBC

Oracle: How to Connect to Oracle via JDBC

Redshift: How to Connect to Redshift via JDBC

SQLite: How to Connect to SQLite via JDBC