Learn how to interact with Azure services using JavaScript.
This sample demonstrates how to programmatically create a new Azure SQL Database instance using the Azure SDK for JavaScript. This is a fundamental operation for setting up your database infrastructure in Azure.
npm install @azure/arm-sql @azure/identityThis JavaScript code snippet uses the @azure/arm-sql and @azure/identity packages to create a new SQL database.
import { SqlManagementClient } from "@azure/arm-sql";
import { DefaultAzureCredential } from "@azure/identity";
async function createSqlDatabase() {
// Replace with your Azure subscription ID, resource group name, and SQL server name
const subscriptionId = "YOUR_SUBSCRIPTION_ID";
const resourceGroupName = "YOUR_RESOURCE_GROUP_NAME";
const sqlServerName = "YOUR_SQL_SERVER_NAME";
const databaseName = "myNewJsDatabase"; // Name for the new database
const credential = new DefaultAzureCredential();
const client = new SqlManagementClient(credential, subscriptionId);
console.log(`Creating database "${databaseName}" on server "${sqlServerName}"...`);
try {
const result = await client.databases.beginCreateOrUpdateAndWait(
resourceGroupName,
sqlServerName,
databaseName,
{
location: "eastus", // Replace with your desired Azure region
// You can specify other properties like sku, collation, etc.
sku: {
name: "Basic" // Example: Basic, Standard, Premium tiers available
}
}
);
console.log(`Database "${result.name}" created successfully!`);
console.log(`Database ID: ${result.id}`);
console.log(`Provisioning State: ${result.provisioningState}`);
} catch (error) {
console.error(`Error creating database: ${error.message}`);
throw error;
}
}
// Call the function to create the database
createSqlDatabase().catch(err => {
console.error("An unexpected error occurred:", err);
});
This script initializes a SqlManagementClient using Azure credentials. It then calls the beginCreateOrUpdateAndWait method, providing the necessary resource group, server name, and the desired database name. The optional location and sku properties allow you to configure the database's region and performance tier. The AndWait suffix ensures that the operation completes before the function returns.
Upon successful execution, you should see output similar to this in your console:
Creating database "myNewJsDatabase" on server "your-sql-server-name"...
Database "myNewJsDatabase" created successfully!
Database ID: /subscriptions/YOUR_SUBSCRIPTION_ID/resourceGroups/YOUR_RESOURCE_GROUP_NAME/providers/Microsoft.Sql/servers/YOUR_SQL_SERVER_NAME/databases/myNewJsDatabase
Provisioning State: Succeeded
location property must match the region of your existing SQL Server.sku.name based on your performance and cost requirements. Refer to Azure SQL Database pricing tiers for details.YOUR_SUBSCRIPTION_ID, YOUR_RESOURCE_GROUP_NAME, and YOUR_SQL_SERVER_NAME with your actual Azure resource details.After successfully creating your database, you can explore other samples to: