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
- An Azure Database for MySQL server instance. If you don't have one, create one first.
- Application code (e.g., Python, Java, Node.js).
- Appropriate database drivers or libraries for your application's programming language.
1. Obtaining Connection Details
You'll need the following details to connect to your Azure Database for MySQL server:
- Server name: The fully qualified domain name of your server (e.g.,
your-server-name.mysql.database.azure.com). - Server admin login name: The username you specified during server creation.
- Password: The password for the server admin login.
- Database name: The name of the database you want to connect to. You might need to create this database first.
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.
- Navigate to your Azure Database for MySQL server in the Azure portal.
- Under Settings, click Connection security.
- Click Add current client IP address or configure custom rules.
- For development, you might enable "Allow access to Azure services".
- Click Save.
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
- Use Connection Pooling: For applications with frequent database access, connection pooling significantly improves performance by reusing existing connections.
- Secure Credentials: Avoid hardcoding credentials directly in your code. Use environment variables, configuration files, or Azure Key Vault to manage secrets securely.
- SSL/TLS Encryption: Enforce SSL/TLS connections to encrypt data in transit between your application and the database. Configure your connection string to use SSL.
- Error Handling: Implement robust error handling and logging to diagnose and resolve connection issues effectively.
- Read Replicas: For read-heavy workloads, consider setting up read replicas to distribute the read traffic and improve performance.
Next Steps
Now that you can connect to your Azure Database for MySQL instance, explore other topics: