MSDN Documentation

Connecting Your Application to Azure Database for MySQL

This tutorial guides you through connecting your application to an Azure Database for MySQL instance. We'll cover common connection methods and best practices.

Prerequisites

1. Obtaining Connection Details

You'll need the following details to connect to your Azure Database for MySQL server:

You can find these details on the Overview page of your Azure Database for MySQL server in the Azure portal.

2. Configuring Firewall Rules

By default, Azure Database for MySQL is protected by a firewall. You need to allow access from your application's IP address or range. For development purposes, you can allow all Azure IP addresses.

  1. Navigate to your Azure Database for MySQL server in the Azure portal.
  2. Under Settings, click Connection security.
  3. Click Add current client IP address or configure custom rules.
  4. For development, you might enable "Allow access to Azure services".
  5. Click Save.
Security Note: For production environments, always restrict firewall rules to the minimum necessary IP addresses or IP ranges to enhance security.

3. Connecting with Sample Code

The following examples show how to connect using popular programming languages.

Python (using mysql-connector-python)


import mysql.connector

try:
    conn = mysql.connector.connect(
        host='your-server-name.mysql.database.azure.com',
        user='your_username',
        password='your_password',
        database='your_database'
    )
    cursor = conn.cursor()
    print("Successfully connected to Azure Database for MySQL!")

    # Example query
    cursor.execute("SELECT @@VERSION;")
    db_version = cursor.fetchone()
    print(f"Database version: {db_version[0]}")

except mysql.connector.Error as err:
    print(f"Error connecting to MySQL: {err}")

finally:
    if 'cursor' in locals() and cursor:
        cursor.close()
    if 'conn' in locals() and conn and conn.is_connected():
        conn.close()
        print("Connection closed.")
            

Node.js (using mysql package)


const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'your-server-name.mysql.database.azure.com',
    user: 'your_username',
    password: 'your_password',
    database: 'your_database'
});

connection.connect(err => {
    if (err) {
        console.error('Error connecting to MySQL:', err.stack);
        return;
    }
    console.log('Successfully connected to Azure Database for MySQL as id', connection.threadId);

    // Example query
    connection.query('SELECT @@VERSION;', (error, results, fields) => {
        if (error) throw error;
        console.log('Database version:', results[0]['@@VERSION']);
        connection.end();
        console.log('Connection closed.');
    });
});
            

Java (using JDBC)

Add the MySQL Connector/J dependency to your project (e.g., Maven or Gradle). Example for Maven:


<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version><!-- Use the latest version -->
</dependency>
            

Connection code:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class AzureMySqlConnect {
    public static void main(String[] args) {
        String url = "jdbc:mysql://your-server-name.mysql.database.azure.com:3306/your_database?serverTimezone=UTC";
        String user = "your_username";
        String password = "your_password";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT @@VERSION")) {

            System.out.println("Successfully connected to Azure Database for MySQL!");

            if (rs.next()) {
                System.out.println("Database version: " + rs.getString(1));
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error connecting to MySQL.");
        }
    }
}
            

4. Best Practices

Next Steps

Now that you can connect to your Azure Database for MySQL instance, explore other topics: