Python – Connect and Query
This example shows how to connect to Azure Database for MySQL using mysql-connector-python, create a table, insert data, and run a query.
import mysql.connector
config = {
'user': 'myadmin',
'password': 'MySecurePassword!',
'host': 'myserver.mysql.database.azure.com',
'database': 'sampledb',
'ssl_ca': '/path/to/BaltimoreCyberTrustRoot.crt.pem',
'ssl_verify_cert': True
}
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE IF NOT EXISTS employees ("
"id INT AUTO_INCREMENT PRIMARY KEY, "
"name VARCHAR(255) NOT NULL, "
"title VARCHAR(255) NOT NULL"
")"
)
cursor.execute(
"INSERT INTO employees (name, title) VALUES "
"('Alice Johnson', 'Engineer'), "
"('Bob Smith', 'Manager')"
)
conn.commit()
cursor.execute("SELECT id, name, title FROM employees")
for row in cursor.fetchall():
print(row)
cursor.close()
conn.close()Node.js – Connect and Query
Using the mysql2 library to perform similar operations in Node.js.
const mysql = require('mysql2/promise');
async function main() {
const connection = await mysql.createConnection({
host: 'myserver.mysql.database.azure.com',
user: 'myadmin',
password: 'MySecurePassword!',
database: 'sampledb',
ssl: {
ca: require('fs').readFileSync('/path/to/BaltimoreCyberTrustRoot.crt.pem')
}
});
await connection.execute(`CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL
)`);
await connection.execute(
`INSERT INTO employees (name, title) VALUES
('Alice Johnson', 'Engineer'),
('Bob Smith', 'Manager')`
);
const [rows] = await connection.execute('SELECT id, name, title FROM employees');
console.table(rows);
await connection.end();
}
main().catch(console.error);Java – Connect and Query
Sample using the MySQL Connector/J driver.
import java.sql.*;
public class MySQLAzureSample {
public static void main(String[] args) {
String url = "jdbc:mysql://myserver.mysql.database.azure.com:3306/sampledb?useSSL=true&requireSSL=true";
String user = "myadmin@myserver";
String password = "MySecurePassword!";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS employees (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(255) NOT NULL, " +
"title VARCHAR(255) NOT NULL" +
")"
);
stmt.executeUpdate(
"INSERT INTO employees (name, title) VALUES " +
"('Alice Johnson', 'Engineer'), " +
"('Bob Smith', 'Manager')"
);
ResultSet rs = stmt.executeQuery("SELECT id, name, title FROM employees");
while (rs.next()) {
System.out.printf("%d | %s | %s%n",
rs.getInt("id"),
rs.getString("name"),
rs.getString("title"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}Explore other language samples from the sidebar or consult the API reference for more details.