Skip to main content

Connect with Java Early availability

Connect to an Aiven for AlloyDB Omni database from Java, using JDBC Driver.

Prerequisites

  • Aiven for AlloyDB Omni service running

  • If you have an Apache 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
  • Binary JAR file of the JDBC driver downloaded

Connect to a service

  1. Create a file named AlloyDBOmniExample.java with the following content:

    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 opens a connection to the database, runs a query checking the database version, and prints the response.

  2. Run the code using the following command, replacing the placeholders for connection parameters with the values available on the Overview page of your service in the Aiven Console:

    javac AlloyDBOmniExample.java && java -cp postgresql-42.2.24.jar:. AlloyDBOmniExample -host HOST -port PORT -database DATABASE -username avnadmin -password PASSWORD

    The connection parameters to be replaced in the command:

    VariableDescription
    HOSTHostname for Aiven for AlloyDB Omni service connection
    PORTPort for Aiven for AlloyDB Omni service connection
    DATABASEDatabase name for Aiven for AlloyDB Omni service connection
    PASSWORDavnadmin password

Expect output like:

Version: PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by [...]