首頁  >  問答  >  主體

將 Azure SQL 資料庫連接到 .NET 項目

我已經使用 dotnet 建立了一個 Web API,這是我第一次使用 Azure(或任何其他雲端平台)來託管 Web 應用程式。我使用 EntityFramework 和 MySQL 資料庫來建立我的專案。

我使用DbConnectionString = "Server=localhost;Database=hms;Uid='{root-user}';Pwd={pw};" 作為我的SQL 資料庫的連接字串,現在我想知道如何我將其與我創建的Azure SQL 資料庫連接。我在Azure伺服器的防火牆存取中新增了我的IP位址,並嘗試將連接字串變更為DbConnectionString = "Server=server.database.windows.net:1433;Database=hms;Uid='{root -user}';Pwd= {pw};" 但它給了錯誤 已引發異常,可能是由於暫時性故障。當我在新增遷移後嘗試更新資料庫時,請考慮透過將「EnableRetryOnFailure()」新增至「UseMySql」call. 來啟用暫時性錯誤復原能力。

我想知道我做錯了什麼或我還需要做什麼才能讓它運行。蒂亞。

P粉555682718P粉555682718204 天前289

全部回覆(1)我來回復

  • P粉998920744

    P粉9989207442024-03-29 12:21:37

    1. 我建立了一個包含一張表格的 Azure SQL 資料庫。
    2. 表中的資料如下

    3.使用C#建立控制台應用程式。

    1. 將套件 Microsoft.Data.SqlClient 加入專案中。

    2. 在 Program.cs 檔案中加入了以下程式碼,

    [Taking reference from here](https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-dotnet-visual-studio?view=azuresql), I created a replica of the program.cs file as shown:
    using System;
    using Microsoft.Data.SqlClient;
    using System.Text;
    namespace sqltest
    {
    class Program
     {
      static void Main(string[] args)
      {
    try
     {
     SqlConnectionStringBuilder builder  = new SqlConnectionStringBuilder();
     builder.DataSource = "yourservername.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");
    
    //String sql = "SELECT * FROM dbo.Persons";
    String sql = "SELECT LastName, FirstName FROM dbo.Persons";
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
     connection.Open();
     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.ReadLine();
       }
      }
    }

    6.使用上面的程式碼,我連接到 Azure SQL 並從資料庫檢索資料。

    1. 執行應用程式並從 Azure Sql 資料庫取得數據,如下所示,

    參考連結:

    #https://learn.microsoft.com/en-us/visualstudio/azure/azure-sql-database-add-connected-service?view=vs-2022

    回覆
    0
  • 取消回覆