如何使用 visual studio 连接到 azure SQL 服务器

How to connect to azure SQL server using visual studio

我有一个由 Cosmos DB 触发的 azure 函数。我从 JSON 文件获取数据并将其发送到我在 Azure 上的 SQL 数据库。 我想知道我是否可以使用 Visual Studio 直接连接到 Azure SQL? 我已经通过门户连接到它一次,但我看不到我在 Visual Studio 中的 View/Cloud Explorer 下连接到我的数据库。 该数据库仅列在 View/SQL Server Object Explorer 下。我假设此连接是通过我的本地计算机进行的,而不是直接连接到云。 这是我的代码:

        public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([CosmosDBTrigger(
            databaseName: "ToDoList",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDB",
            LeaseCollectionName = "leases")]IReadOnlyList<Document> input, ILogger log)
        {
            if (input != null && input.Count > 0)
            {
                var cnnString = "Server=tcp:server.database.windows.net,1433;Initial Catalog=myDatabase;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
                using (var sqlConnection = new SqlConnection(cnnString))
                {
                    sqlConnection.Open();
                    var cmd = new SqlCommand
                    {
                        CommandText = @"insert into [dbo].[Player] ([User],[Timestamp] values(@User,@Timestamp)",
                        CommandType = CommandType.Text,
                        Connection = sqlConnection,
                    };

                    var record = new Record();
                    //set parameters
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@User", record.Email));
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Timestamp", record.Timestamp));

                    //Execute command
                    await cmd.ExecuteNonQueryAsync();
                }         
            }
        }
    }

您可以在 Visual Studio Server explorer

中看到 Azure SQL 数据库

注意:您需要使用以下工具连接Azure Sql服务器。

我应该选择哪个工具?

  • 您要管理 SQL 服务器实例或数据库吗? Windows、Linux 或 Mac 上的轻量级编辑器?选择 Azure 数据 工作室

  • 您要在 Windows 上管理 SQL 服务器实例或数据库吗 具有完整的 GUI 支持?选择 SQL Server Management Studio (SSMS)

  • 是否要创建或维护数据库代码,包括编译 Windows 上的时间验证、重构和设计器支持?选择 SQL 服务器数据工具 (SSDT)

  • 你想用命令行工具查询 SQL 服务器吗 具有 IntelliSense、语法高亮显示等功能?选择 mssql-cli

  • 你想在轻量级编辑器中编写T-SQL脚本吗 Windows、Linux 还是 Mac?选择Visual Studio代码mssql 分机

详情请参考“SQL Tools and Utilities for SQL Server, Azure SQL Database, and Azure SQL Data Warehouse”。

您可以尝试以下步骤使用 Visual Studio连接到 Azure SQL 服务器:

打开 Visual Studio 并登录。

单击 打开 Cloud Explorer 查看所有订阅select 您的订阅

Select 您的订阅 => Select SQL 数据库 => Select 您的数据库 =>右键单击并select 打开SQL 服务器对象资源管理器 => 输入凭据并连接。

连接数据库后=> 右击 => 新建查询 => 输入查询 => 在查询的顶部你会发现 available databases (Shift+Alt+PgDn) 然后点击 execute (Ctrl+Shift+E).

希望对您有所帮助。