快速入門:使用 .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 關閉應用程式視窗。

下一步