你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用 .NET (C#) 查询数据库

适用于:Azure SQL 数据库Azure SQL 托管实例Azure Synapse Analytics

在本快速入门中,将使用 .NET 和 C# 代码连接到数据库。 然后,将运行 Transact-SQL 语句来查询数据。 本快速入门适用于 Windows、Linux 和 macOS,并利用统一的 .NET 平台。

先决条件

若要完成本快速入门,你需要:

创建新的 .NET 项目

  1. 打开命令提示符,然后创建一个名为 sqltest 的文件夹。 导航到此文件夹,并运行以下命令。

    dotnet new console
    

    此命令将创建新的应用项目文件,包括初始 C# 代码文件 (Program.cs)、XML 配置文件 (sqltest.csproj) 和所需的二进制文件。

  2. 在上面使用的命令提示符处,运行以下命令。

    dotnet add package Microsoft.Data.SqlClient
    

    此命令会将 Microsoft.Data.SqlClient 包添加到项目。

插入代码以查询 Azure SQL 数据库中的数据库

  1. Visual Studio Code 等文本编辑器中,打开 Program.cs。

  2. 将内容替换为以下代码,为服务器、数据库、用户名和密码添加相应的值。

注意

若要使用 ADO.NET 连接字符串,请将代码中设置服务器、数据库、用户名和密码的 4 行替换为以下行。 在字符串中,设置用户名和密码。

builder.ConnectionString="<your_ado_net_connection_string>";

using Microsoft.Data.SqlClient;

namespace sqltest
{
    class Program
    {
        static void Main(string[] args)
        {
            try 
            { 
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                builder.DataSource = "<your_server.database.windows.net>"; 
                builder.UserID = "<your_username>";            
                builder.Password = "<your_password>";     
                builder.InitialCatalog = "<your_database>";
         
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    Console.WriteLine("\nQuery data example:");
                    Console.WriteLine("=========================================\n");
                    
                    connection.Open();       

                    String sql = "SELECT name, collation_name FROM sys.databases";

                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
                            }
                        }
                    }                    
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("\nDone. Press enter.");
            Console.ReadLine(); 
        }
    }
}

运行代码

  1. 在提示符处,运行以下命令。

    dotnet restore
    dotnet run
    
  2. 验证是否返回了行,你的输出可能包含其他值。

    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.
    
  3. 选择 Enter 关闭应用程序窗口。

后续步骤