Azure Database for MySQL Samples

Explore a curated collection of code samples to help you connect, manage, and optimize your Azure Database for MySQL instances.

Connection

Connect to Azure MySQL using Python

Learn how to establish a secure connection to your Azure Database for MySQL using the popular Python programming language and the `mysql.connector` library.

Management

Create a Firewall Rule with Azure CLI

Automate the process of configuring network access by creating firewall rules for your Azure Database for MySQL using the Azure Command-Line Interface.

Querying

Perform Basic CRUD Operations with Node.js

Implement Create, Read, Update, and Delete operations on your database tables using Node.js and a robust MySQL driver.

Performance

Monitor Query Performance with PHP

Discover how to track and analyze query performance to identify bottlenecks and optimize your application's interaction with Azure Database for MySQL.

Backup/Restore

Automated Backups with PowerShell

Set up automated backup schedules and explore restore procedures using PowerShell scripts for reliable data protection.

Advanced

Integrate with Azure Functions

Build serverless applications by connecting your Azure Database for MySQL to Azure Functions for event-driven data processing.

Connecting to Azure Database for MySQL using Python

This sample demonstrates how to establish a secure connection to your Azure Database for MySQL instance using Python. Ensure you have the `mysql-connector-python` library installed (`pip install mysql-connector-python`).

Python
import mysql.connector

host = "your-server-name.mysql.database.azure.com"
user = "your-username"
password = "your-password"
database = "your-database-name"

try:
    cnx = mysql.connector.connect(
        user=user,
        password=password,
        host=host,
        database=database
    )

    cursor = cnx.cursor()
    print("Successfully connected to Azure Database for MySQL!")

    # Example query:
    cursor.execute("SELECT @@VERSION")
    version = cursor.fetchone()
    print("Database version: ", version)

except mysql.connector.Error as err:
    print(f"Error: {err}")
finally:
    if cnx and cnx.is_connected():
        cursor.close()
        cnx.close()
        print("Connection closed.")

Creating a Firewall Rule with Azure CLI

This example shows how to use the Azure CLI to create a firewall rule, allowing specific IP addresses or ranges to access your Azure Database for MySQL server.

Bash
# Replace placeholders with your actual values
AZURE_RESOURCE_GROUP="YourResourceGroupName"
AZURE_SERVER_NAME="YourAzureMySQLServerName"
RULE_NAME="AllowMyIP"
START_IP_ADDRESS="0.0.0.0" # Example: Your public IP address
END_IP_ADDRESS="0.0.0.0" # Example: Your public IP address

az mysql server firewall-rule create \
    --resource-group $AZURE_RESOURCE_GROUP \
    --server $AZURE_SERVER_NAME \
    --name $RULE_NAME \
    --start-ip-address $START_IP_ADDRESS \
    --end-ip-address $END_IP_ADDRESS

# To allow all IPs (use with caution):
az mysql server firewall-rule create \
    --resource-group $AZURE_RESOURCE_GROUP \
    --server $AZURE_SERVER_NAME \
    --name "AllowAll" \
    --start-ip-address "0.0.0.0" \
    --end-ip-address "255.255.255.255"

Performing Basic CRUD Operations with Node.js

This Node.js example illustrates how to perform fundamental Create, Read, Update, and Delete operations on your Azure Database for MySQL. Ensure you have the `mysql` package installed (`npm install mysql`).

JavaScript
const mysql = require('mysql');

// Database connection configuration
const connection = mysql.createConnection({
    host: 'your-server-name.mysql.database.azure.com',
    user: 'your-username',
    password: 'your-password',
    database: 'your-database-name',
    ssl: {
        rejectUnauthorized: false // Recommended for production, use a proper CA cert
    }
});

connection.connect(function(err) {
    if (err) {
        console.error('Error connecting: ' + err.stack);
        return;
    }
    console.log('Connected as id ' + connection.threadId);

    // --- Create Operation ---
    const newUser = { name: 'Alice', email: 'alice@example.com' };
    connection.query('INSERT INTO users SET ?', newUser, function(error, results, fields) {
        if (error) throw error;
        console.log('User inserted with ID: ', results.insertId);

        // --- Read Operation ---
        connection.query('SELECT * FROM users WHERE id = ?', [results.insertId], function(error, results, fields) {
            if (error) throw error;
            console.log('User found: ', results[0]);

            // --- Update Operation ---
            connection.query('UPDATE users SET email = ? WHERE id = ?', ['alice.updated@example.com', results[0].id], function(error, results, fields) {
                if (error) throw error;
            console.log('User email updated.');

            // --- Delete Operation ---
            connection.query('DELETE FROM users WHERE id = ?', [results[0].id], function(error, results, fields) {
                if (error) throw error;
            console.log('User deleted.');
            connection.end();
        });
        });
    });

});