Skip to main content

Connect to Aiven for MySQL® with Java

This example connects your Java application to an Aiven for MySQL® service.

Variables

These are the placeholders you need to replace in the code sample:

VariableDescription
MYSQL_HOSTHost name for the connection, from Aiven Console > the Overview page of your service > the Connection information section
MYSQL_PORTPort number to use, from Aiven Console > the Overview page of your service > the Connection information section
MYSQL_PASSWORDPassword for avnadmin user
MYSQL_DATABASEDatabase to connect

Prerequisites

  • JDK 1.8+
  • MySQL JDBC Driver, which could be downloaded in the following ways:
    • Manually from MySQL Community Downloads

    • Or using maven

      mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=mysql:mysql-connector-java:8.0.28:jar -Ddest=mysql-driver-8.0.28.jar

Code

Add the following to MySqlExample.java:

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 MySqlExample {
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("com.mysql.cj.jdbc.Driver");
try (final Connection connection =
DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + databaseName + "?sslmode=require", userName, password);
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT version() AS 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 MySQL client and connects to the database. It fetches version of MySQL and prints it the output.

Run the code after replacement of the placeholders with values for your project:

javac MySqlExample.java && java -cp mysql-driver-8.0.28.jar:. MySqlExample -host MYSQL_HOST -port MYSQL_PORT -database MYSQL_DATABASE -username avnadmin -password MYSQL_PASSWORD

If the script runs successfully, the output will be the values that were inserted into the table:

Version: 8.0.26

Now that your application is connected, you are all set to use Java with Aiven for MySQL.