如何将用户添加到Azure SQL数据库?

wdebmtf2  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(140)

如何使用新的Azure Sdk以编程方式将SQL用户添加到数据库?
我可以使用以下方法成功创建数据库:

var client = new ArmClient(credential);
var subscription = await client.GetDefaultSubscriptionAsync();       

// Only one server available
var sqlServers = subscription.GetSqlServers().ToList();
var sqlServer = sqlServers.FirstOrDefault();

var data = new SqlDatabaseData(AzureLocation.GermanyWestCentral) {
                Location = "westeurope",
                Sku = new SqlSku("P1") {
                    Name = "Basic",
                    Tier = "Basic",
                },
                Collation = "SQL_Latin1_General_CP1_CI_AS",
                MaxSizeBytes = 1073741824, 
            };

sqlServer.GetSqlDatabases().CreateOrUpdate(WaitUntil.Completed, databaseName, data);

任何帮助将不胜感激。
最好的问候

li9yvcax

li9yvcax1#

  • 我已经在portal中创建了Azure keyvaultAzure数据库
  • 在keyvault中添加了secret,在创建secret时,我将SQL连接字符串作为值。

下面是我的代码。

using System;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System.Data.SqlClient;

namespace Example
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Initialize Azure credentials
            var credential = new DefaultAzureCredential();

            // Retrieve the SQL database connection string from Azure Key Vault
            var secretClient = new SecretClient(new Uri("https://enter your keyvault name.vault.azure.net/"), credential);
            var connectionString = (await secretClient.GetSecretAsync("secret name")).Value.Value;

            // Connect to the SQL database
            using var connection = new SqlConnection(connectionString);
            await connection.OpenAsync();

            // Create a new SQL user with the desired credentials
            var command = new SqlCommand("CREATE USER Admin21 WITH PASSWORD = 'password'", connection);
            await command.ExecuteNonQueryAsync();

            // Close the database connection
            await connection.CloseAsync();

            Console.WriteLine("SQL user created successfully!");
        }
    }
}

输出:

我能够连接数据库中创建的用户。

相关问题