How to export SQL Database directly to blob storage programmatically

前端 未结 4 2045
野性不改
野性不改 2020-12-20 02:40

I need to programmatically backup/export a SQL Database (either in Azure, or a compatible-one on-prem) to Azure Storage, and restore it to another SQL Database. I would lik

4条回答
  •  旧巷少年郎
    2020-12-20 03:34

    You can use Microsoft.Azure.Management.Fluent to export your database to a .bacpac file and store it in a blob. To do this, there are few things you need to do.

    1. Create an AZAD (Azure Active Directory) application and Service Principal that can access resources. Follow this link for a comprehensive guide.
    2. From the first step, you are going to need "Application (client) ID", "Client Secret", and "Tenant ID".
    3. Install Microsoft.Azure.Management.Fluent NuGet packages, and import Microsoft.Azure.Management.Fluent, Microsoft.Azure.Management.ResourceManager.Fluent, and Microsoft.Azure.Management.ResourceManager.Fluent.Authentication namespaces.
    4. Replace the placeholders in the code snippets below with proper values for your usecase.
    5. Enjoy!

          var principalClientID = "";
          var principalClientSecret = "";
          var principalTenantID = "";
      
      
          var sqlServerName = " (without '.database.windows.net'>";
          var sqlServerResourceGroupName = "";
      
      
          var databaseName = "";
          var databaseLogin = "";
          var databasePassword = "";
      
      
          var storageResourceGroupName = "";
          var storageName = "";
          var storageBlobName = "";
      
      
          var bacpacFileName = "myBackup.bacpac";
      
      
          var credentials = new AzureCredentialsFactory().FromServicePrincipal(principalClientID, principalClientSecret, principalTenantID, AzureEnvironment.AzureGlobalCloud);
          var azure = await Azure.Authenticate(credentials).WithDefaultSubscriptionAsync();
      
          var storageAccount = await azure.StorageAccounts.GetByResourceGroupAsync(storageResourceGroupName, storageName);
      
      
          var sqlServer = await azure.SqlServers.GetByResourceGroupAsync(sqlServerResourceGroupName, sqlServerName);
          var database = await sqlServer.Databases.GetAsync(databaseName);
      
          await database.ExportTo(storageAccount, storageBlobName, bacpacFileName)
                  .WithSqlAdministratorLoginAndPassword(databaseLogin, databasePassword)
                  .ExecuteAsync();
      

提交回复
热议问题