Connect to Aiven for MySQL® with Java
This example connects your Java application to an Aiven for MySQL® service.
Variables
Replace the following placeholders in the code sample:
Variable | Description |
---|---|
MYSQL_HOST | Host name for the connection, from Aiven Console > the Overview page of your service > the Connection information section |
MYSQL_PORT | Port number to use, from Aiven Console > the Overview page of your service > the Connection information section |
MYSQL_PASSWORD | Password for avnadmin user |
MYSQL_DATABASE | Database to connect |
Prerequisites
- JDK 1.8+
- MySQL JDBC Driver, which you can install:
-
Manually from MySQL Community Downloads
-
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.