MSDN

Azure Database for MySQL – Java

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

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

IssueResolution
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