Connect with Java
This example connects to PostgreSQL® service from Java, making use of JDBC Driver.
Variables
These are the placeholders you will need to replace in the code sample:
Variable | Description |
---|---|
HOSTNAME | Hostname for PostgreSQL connection, from the service overview page |
PORT | Port for PostgreSQL connection, from the service overview page |
DATABASE | Database Name for PostgreSQL connection, from the service overview page |
PASSWORD | avnadmin password, from the service overview page |
Prerequisites
For this example you will need the PostgreSQL Driver:
-
If you have maven version >= 2+, run:
mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=org.postgresql:postgresql:42.3.2:jar -Ddest=postgresql-42.3.2.jar
-
Download the jar at https://jdbc.postgresql.org/download/
Code
Add the following to PostgresqlExample.java
and replace the
placeholder with the PostgreSQL URI:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
public class PostgresqlExample {
public static void main(String[] args) throws ClassNotFoundException {
String host, port, databaseName, userName, password;
host = port = databaseName = userName = password = null;
for (int i = 0; i < args.length - 1; i++) {
switch (args[i].toLowerCase(Locale.ROOT)) {
case "-host": host = args[++i]; break;
case "-username": userName = args[++i]; break;
case "-password": password = args[++i]; break;
case "-database": databaseName = args[++i]; break;
case "-port": port = args[++i]; break;
}
}
// JDBC allows to have nullable username and password
if (host == null || port == null || databaseName == null) {
System.out.println("Host, port, database information is required");
return;
}
Class.forName("org.postgresql.Driver");
try (final Connection connection =
DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/" + databaseName + "?sslmode=require", userName, password);
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT version()")) {
while (resultSet.next()) {
System.out.println("Version: " + resultSet.getString("version"));
}
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
This code creates a PostgreSQL client and opens a connection to the database. Then runs a query checking the database version and prints the response
Before running the code, change:
- HOST to
HOSTNAME
- PORT: to
PORT
- DATABASE to
DATABASE
- PASSWORD to
PASSWORD
To run the code:
javac PostgresqlExample.java && java -cp postgresql-42.2.24.jar:. PostgresqlExample -host HOST -port PORT -database DATABASE -username avnadmin -password PASSWORD
If the script runs successfully, the outputs should be the PostgreSQL version running in your service like:
Version: PostgreSQL 13.4 on x86_64-pc-linux-gnu, compiled by gcc, a cdda7373b4 p 9751fce1e6, 64-bit