Azure Database Samples

Ready‑to‑run code snippets for Azure SQL, Cosmos DB, MySQL, PostgreSQL, and more.

SQL Database – .NET Core

Connect to Azure SQL Database and execute a simple query using Microsoft.Data.SqlClient.

using var connection = new SqlConnection(Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTION_STRING"));
await connection.OpenAsync();
var command = new SqlCommand("SELECT TOP 10 Name FROM Products;", connection);
using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
    Console.WriteLine(reader.GetString(0));
}
Cosmos DB – JavaScript SDK

Insert and query documents in a Cosmos DB container using the Node.js SDK.

const { CosmosClient } = require("@azure/cosmos");
const client = new CosmosClient(process.env.COSMOS_CONNECTION_STRING);
const database = client.database("SampleDB");
const container = database.container("Items");

await container.items.create({ id: "item1", name: "Azure Sample" });
const { resources } = await container.items.query("SELECT * FROM c").fetchAll();
console.log(resources);
MySQL – Python

Connect to Azure Database for MySQL and fetch rows using mysql-connector-python.

import mysql.connector
cnx = mysql.connector.connect(
    host=os.getenv("MYSQL_HOST"),
    user=os.getenv("MYSQL_USER"),
    password=os.getenv("MYSQL_PASSWORD"),
    database="sampledb"
)
cursor = cnx.cursor()
cursor.execute("SELECT name FROM employees LIMIT 5;")
for (name,) in cursor:
    print(name)
cnx.close()
PostgreSQL – Go

Execute a query against Azure Database for PostgreSQL using pgx.

package main
import (
    "context"
    "fmt"
    "os"
    "github.com/jackc/pgx/v5"
)
func main() {
    conn, _ := pgx.Connect(context.Background(), os.Getenv("POSTGRES_URL"))
    rows, _ := conn.Query(context.Background(), "SELECT title FROM books LIMIT 3")
    for rows.Next() {
        var title string
        rows.Scan(&title)
        fmt.Println(title)
    }
    conn.Close(context.Background())
}