Connect to Azure Database for MySQL using Java
This guide shows how to connect to an Azure Database for MySQL server from a Java application using the MySQL Connector/J driver.
Prerequisites
- Azure Database for MySQL server provisioned.
- Java Development Kit (JDK) 8 or higher.
- Maven or Gradle for dependency management.
- MySQL Connector/J (8.0.33 or later).
1. Add the MySQL Connector/J Dependency
Using Maven:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
Using Gradle:
implementation 'mysql:mysql-connector-j:8.0.33'
2. Connection String
Replace {your-server}, {your-database}, {your-username}, and {your-password} with your actual values.
String url = "jdbc:mysql://{your-server}.mysql.database.azure.com:3306/{your-database}?useSSL=true&requireSSL=true";
String user = "{your-username}@{your-server}";
String password = "{your-password}";
3. Sample Java Code
Below is a minimal program that connects to the MySQL server, runs a simple query, and prints the results.
// File: MySqlDemo.java
import java.sql.*;
public class MySqlDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://myserver.mysql.database.azure.com:3306/sampledb?useSSL=true&requireSSL=true";
String user = "myuser@myserver";
String password = "MySuperSecretPassword!";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT NOW() AS current_time")) {
while (rs.next()) {
System.out.println("Current time from Azure MySQL: " + rs.getString("current_time"));
}
} catch (SQLException e) {
System.err.println("Connection failed!");
e.printStackTrace();
}
}
}
4. Enable TLS/SSL
Azure Database for MySQL enforces SSL connections. Ensure the connection string includes useSSL=true&requireSSL=true. If you need to trust the Azure certificate, add the following JVM option:
-Dcom.mysql.cj.sslMode=REQUIRED
5. Common Troubleshooting
| Issue | Resolution |
|---|---|
| Unable to connect (Communications link failure) | Verify that your client IP is allowed in the server's firewall rules. |
| Authentication error | Use the format username@servername and ensure the password is correct. |
| SSLHandshakeException | Confirm that useSSL=true is set and the Java runtime trusts the Azure CA certificate. |
6. Next Steps
- Explore advanced Java topics such as connection pooling with HikariCP.
- Integrate with Spring Boot for rapid development.
- Review performance tuning guidelines.