适用于:Azure SQL 数据库
Azure SQL 托管实例
Azure Synapse Analytics
在本快速入门中,将使用 .NET 和 C# 代码连接到数据库。 然后,将运行 Transact-SQL 语句来查询数据。 本快速入门适用于 Windows、Linux 和 macOS,并利用统一的 .NET 平台。
提示
本免费学习模块介绍如何开发和配置可在 Azure SQL 数据库中查询数据库的 ASP.NET 应用程序
先决条件
若要完成本快速入门,需要以下项:
- 具有活动订阅的 Azure 帐户。 创建试用版订阅。 
- 专门用于运行查询的数据库。 - 可以根据下述快速入门之一,创建数据库,然后对其进行配置: - 行动 - SQL 数据库 - SQL 托管实例 - Azure VM 上的 SQL Server - Azure Synapse Analytics - 创建 - Portal - Portal - Portal - Portal - CLI - CLI - PowerShell - PowerShell - PowerShell - PowerShell - 部署模板 - 部署模板 - 部署模板 - 配置 - 服务器级别 IP 防火墙规则 - 从 VM 进行连接 - 连接设置 - 来自本地的连接 - 连接到 SQL Server 实例 - 获取连接信息 - Azure SQL - Azure SQL - SQL VM - Synapse SQL 
创建新的 .NET 项目
- 打开命令提示符,然后创建一个名为 sqltest 的文件夹。 导航到此文件夹,并运行以下命令。 - dotnet new console- 此命令将创建新的应用项目文件,包括初始 C# 代码文件 (Program.cs)、XML 配置文件 (sqltest.csproj) 和所需的二进制文件。 
- 在上面使用的命令提示符处,运行以下命令。 - dotnet add package Microsoft.Data.SqlClient- 此命令会将 - Microsoft.Data.SqlClient包添加到项目。
插入代码以查询 Azure SQL 数据库中的数据库
- 在 Visual Studio Code 等文本编辑器中,打开 Program.cs。 
- 将内容替换为以下代码,为服务器、数据库、用户名和密码添加相应的值。 
注意
若要使用 ADO.NET 连接字符串,请将代码中设置服务器、数据库、用户名和密码的 4 行替换为以下行。 在字符串中,设置用户名和密码。
builder.ConnectionString="<connection-string>";
using Microsoft.Data.SqlClient;
using System;
using System.Threading.Tasks;
namespace sqltest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var builder = new SqlConnectionStringBuilder
            {
                DataSource = "<your_server.database.chinacloudapi.cn>",
                UserID = "<your_username>",
                Password = "<password>",
                InitialCatalog = "<your_database>"
            };
            var connectionString = builder.ConnectionString;
            try
            {
                await using var connection = new SqlConnection(connectionString);
                Console.WriteLine("\nQuery data example:");
                Console.WriteLine("=========================================\n");
                await connection.OpenAsync();
                var sql = "SELECT name, collation_name FROM sys.databases";
                await using var command = new SqlCommand(sql, connection);
                await using var reader = await command.ExecuteReaderAsync();
                while (await reader.ReadAsync())
                {
                    Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
                }
            }
            catch (SqlException e) when (e.Number == /* specific error number */)
            {
                Console.WriteLine($"SQL Error: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("\nDone. Press enter.");
            Console.ReadLine();
        }
    }
}
记得将 <your_server.database.chinacloudapi.cn>、<your_username>、<password> 和 <your_database> 替换为实际的 SQL Server 详细信息。 此外,将 /* specific error number */ 替换为要处理的实际 SQL 错误号。
运行代码
- 在提示符处,运行以下命令。 - dotnet restore dotnet run
- 验证是否返回了行,输出可能包含其他值。 - Query data example: ========================================= master SQL_Latin1_General_CP1_CI_AS tempdb SQL_Latin1_General_CP1_CI_AS WideWorldImporters Latin1_General_100_CI_AS Done. Press enter.
- 选择 Enter 关闭应用程序窗口。