使用 .NET SDK 建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器執行個體

在本快速入門中,您將瞭解如何使用 .NET 中的 Azure SDK 連結庫來建立、更新和刪除 Azure PostgreSQL 彈性伺服器實例。 適用於 PostgreSQL 的 Azure 資料庫是一項受控服務,可讓您在雲端中執行、管理和調整高可用性 PostgreSQL 資料庫。 您可以使用 .NET SDK,在伺服器上佈建適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體、多部伺服器或多個資料庫。

先決條件

Azure.ResourceManager.PostgreSql 程式庫

程式 Azure.ResourceManager.PostgreSql 庫是適用於 .NET 的 Azure SDK 的一部分,並提供在 Azure 中管理 PostgreSQL 彈性伺服器執行個體的功能。 使用此函式庫,您可以執行與 PostgreSQL 彈性伺服器執行個體相關的各種操作,包括但不限於:

  1. 建立 Azure PostgreSQL 彈性伺服器實例:
    您可以使用指定的組態來建立新的彈性伺服器實例,例如位置、SKU、記憶體和版本。

  2. 更新 Azure PostgreSQL 彈性伺服器執行個體:
    您可以更新現有的 PostgreSQL 彈性伺服器執行個體,包括變更管理員登入、密碼、SKU、儲存和版本等組態。

  3. 刪除 Azure PostgreSQL 彈性伺服器執行個體:
    您可以刪除現有的 Azure PostgreSQL 彈性伺服器執行個體。

  4. 擷取 Azure PostgreSQL 資訊:
    您可以擷取現有 PostgreSQL 彈性伺服器執行個體的詳細資訊,包括其組態、狀態和其他中繼資料。

  5. 管理資料庫:
    您可以在 Azure PostgreSQL 彈性伺服器執行個體內建立、更新、刪除和擷取資料庫。

  6. 管理防火牆規則:
    您可以建立、更新、刪除和擷取執行個體的防火牆規則,以控制存取權。

  7. 管理組態設定:
    你可以管理 Azure PostgreSQL 彈性伺服器實例的設定,包括擷取和更新參數。

登入 Azure

使用適用於 .NET 的 Azure SDK 來建立、更新或刪除適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體之前,您必須使用 Azure CLI 登入您的 Azure 帳戶。

執行登入命令

使用 az CLI 登入您的帳戶

az login

安裝必要的套件

使用下列命令安裝必要套件︰

dotnet add package Azure.Identity
dotnet add package Azure.ResourceManager
dotnet add package Azure.ResourceManager.PostgreSql

安裝這些套件後,請確保在執行建置與執行命令前,每個套件都已列在 .csproj 檔案中。

若要深入了解 .csproj 檔案,請造訪 Web 部署。

Note

如果你在初始設定 .NET 時遇到問題,請參考這個指南。

建立專案

遵循此連結中所提及的步驟,建立新的 .NET 專案

建立伺服器

若要建立 PostgreSQL 彈性伺服器執行個體,請使用下列程式碼建立名為 CreateServer.cs 的檔案。

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;

namespace CreatePostgreSqlFlexibleServer
{
    class Program
 {
        static async Task Main(string[] args)
   {

            TokenCredential credential = new DefaultAzureCredential();
            ArmClient armClient = new ArmClient(credential);
            // Replace with your subscription ID
            string subscriptionId = "subscription-id";
            // Replace with your resource group name
            string resourceGroupName = "resource-group-name";
           // Replace with a unique server name
            string serverName = "server-name";
           // Replace with your desired region
            string location = "region-name";
          // Create the resource identifier for the resource group
            ResourceIdentifier resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
            ResourceGroupResource resourceGroup = await armClient.GetResourceGroupResource(resourceGroupId).GetAsync();
            // Prepare server data
            var serverData = new PostgreSqlFlexibleServerData(location)
            {
              AdministratorLogin = "admin-username",
              AdministratorLoginPassword = "<admin-password>",
              Version = "pgVersion",
              Storage = new PostgreSqlFlexibleServerStorage() { StorageSizeInGB = 128 },
              Sku = new PostgreSqlFlexibleServerSku("Standard_B1ms", PostgreSqlFlexibleServerSkuTier.Burstable),
           };
            try
            {
               ArmOperation<PostgreSqlFlexibleServerResource> operation = await resourceGroup.GetPostgreSqlFlexibleServers().CreateOrUpdateAsync(Azure.WaitUntil.Completed, serverName, serverData);
              PostgreSqlFlexibleServerResource serverResource = operation.Value;
              Console.WriteLine($"PostgreSQL flexible server '{serverResource.Data.Name}' created successfully.");
           }
            catch (Exception ex)
            {
               Console.WriteLine($"An error occurred: {ex.Message}");
            }
   }
  }
}

此範例示範如何使用 Azure Resource Manager 建立 PostgreSQL 彈性伺服器執行個體。 PostgreSql 程式庫。 您可以類似地使用程式庫提供的其他方法來管理 PostgreSQL 彈性伺服器執行個體和相關資源。

以您的資料取代程式碼中的下列參數:

  • subscription-id = 您的 Azure 訂用帳戶識別碼。
  • resource-group-name:你資源團體的名稱。
  • server-name:PostgreSQL 伺服器的唯一名稱。
  • location:伺服器的 Azure 區域。
  • admin-username:系統管理員使用者名稱。
  • admin-password:系統管理員密碼。
  • pgVersion:PostgreSQL 版本 (例如 11、12、13、14、15 或 16)。

Authentication

DefaultAzureCredential 類別會嘗試使用環境變數、受控身分識別或 Azure CLI 等方法進行驗證。 請確定您已設定其中一種方法。

執行檔案

若要執行該檔案,您必須使用 .NET CLI 建置和執行 .cs 檔案。 這將根據程式碼啟動 PostgreSQL 執行個體的建立、更新或刪除程序。

每次您在 .cs 檔案進行任何變更時,都別忘了建置並執行該檔案

使用下列命令執行 .cs 檔案

dotnet build
dotnet run

Note

執行此程式碼將啟動執行個體建立程序,此過程可能需要幾分鐘時間完成。

檢閱已部署的資源

您可以透過 Azure 入口網站、Azure CLI、Azure PowerShell 和其他各種工具來檢閱已部署的彈性伺服器執行個體,以驗證部署並檢閱已部署的資源。

更新伺服器資料

建立 UpdateServerData.cs 檔案。

您也可以使用 Azure PostgreSQL .NET SDK 更新伺服器資料。

例如,您可以使用 CreateOrUpdateAsync 方法來更新版本、管理使用者名稱、密碼等。

CreateOrUpdateAsync 方法會在不存在同名稱執行個體時建立新執行個體;如果同名稱執行個體已存在,則會使用新的伺服器資料更新該執行個體。

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;

namespace UpdateServerData
{
    class Program
 {
        static async Task Main(string[] args)
   {

            TokenCredential credential = new DefaultAzureCredential();
            ArmClient armClient = new ArmClient(credential);
            // Replace with your subscription ID
            string subscriptionId = "subscription-id";
            // Replace with your resource group name
            string resourceGroupName = "resource-group-name";
            // Replace with a unique server name
            string serverName = "server-name";
            // Replace with your desired region
            string location = "region-name";
            ResourceIdentifier resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
            ResourceGroupResource resourceGroup = await armClient.GetResourceGroupResource(resourceGroupId).GetAsync();
            // Prepare server data
            var serverData = new PostgreSqlFlexibleServerData(location)
           {
              // Updating version from a lower version to a higher version
              Version = "16",
           };
            try
             {
               ArmOperation<PostgreSqlFlexibleServerResource> operation = await resourceGroup.GetPostgreSqlFlexibleServers().CreateOrUpdateAsync(Azure.WaitUntil.Completed, serverName, serverData);
               PostgreSqlFlexibleServerResource serverResource = operation.Value;
               Console.WriteLine($"PostgreSQL flexible server '{serverResource.Data.Name}' updated successfully.");
            }
            catch (Exception ex)
            {
              Console.WriteLine($"An error occurred: {ex.Message}");
            }
   }
  }
}

執行該檔案,並使用 'UpdateServerData.cs' 檔案檢閱資源中所做的變更。

清理資源

您可以使用適用於 .NET 的 Azure SDK 刪除彈性伺服器執行個體,以清除已建立的彈性伺服器執行個體。

建立 DeleteServer.cs 檔案並新增下列程式碼。

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;

namespace DeleteServer
{
    class Program
  {
        static async Task Main(string[] args)
   {

            // Replace with your subscription ID
            string subscriptionId = "subscription-id";
            // Replace with your resource group name
            string resourceGroupName = "resource-group-name";
            // Replace with a unique server name
            string serverName = "server-name";
            var credential = new DefaultAzureCredential();
            var armClient = new ArmClient(credential);
            try
            {
                // Get the PostgreSQL flexible server resource
                var postgresServerResourceId = PostgreSqlFlexibleServerResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, serverName);
                var postgresServer = armClient.GetPostgreSqlFlexibleServerResource(postgresServerResourceId);
                // Delete the server
                await postgresServer.DeleteAsync(Azure.WaitUntil.Completed);
                Console.WriteLine($"PostgreSQL flexible server '{serverName}' deleted successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
   }
  }
}

使用您的資料取代下列參數:

  • subscription-id:您自己的訂用帳戶識別碼。
  • resource-group-name:您想要使用的資源群組名稱。 如果資源群組不存在,該指令碼會建立一個新的資源群組。
  • server-name:您已建立的 Azure 資料庫彈性伺服器執行個體名稱。

您也可以刪除透過入口網站、CLI 或 PowerShell 建立的資源群組。 如果您想要使用 CLI 或 PowerShell 將其刪除,請遵循 CLI 和 PowerShell 一節中所提及的步驟。

將預留位置取代為您的詳細資料,然後執行檔案。

或者,您可以使用下列項目來移除資源群組:

  • Azure CLI: az group delete --name <resource_group>
  • PowerShell: Remove-AzResourceGroup -Name <resource_group>
  • Azure 入口網站:瀏覽至資源群組並加以刪除。