[英]How do i connect to a Microsoft SQL Server database to which i normally connect via GlobalProtect using .net6 application
我在我的 Azure Function 應用程序中使用 .net6、Azure Function 版本 4 和 SqlClient。
我有這樣的連接字符串
Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;
通常,我通過提供門戶、用戶名和密碼使用 GlobalProtect 訪問此數據庫。 現在,我正在開發一個將訪問此數據庫的 Azure Function 應用程序,但出現此錯誤
System.Private.CoreLib:執行函數時出現異常:MyAzurefunction。 Core.Net SqlClient 數據提供程序:無法打開登錄請求的服務器“serverName”。 不允許 IP 地址為“MyIpAddress”的客戶端訪問服務器。 要啟用訪問,請使用 Windows Azure 管理門戶或在 master 數據庫上運行 sp_set_firewall_rule 以為此 IP 地址或地址范圍創建防火牆規則。 此更改最多可能需要五分鍾才能生效。
我知道我收到此錯誤是因為我的 IpAddress 無法訪問服務器,但我如何通過我的連接字符串連接到它?
我創建了 azure SQL 數據庫。 數據庫連接字符串:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
圖片供參考:
我在 Visual Studio 中使用 .net 6 創建了函數應用程序。 圖片供參考:
我將它發布到 Azure。 圖片供參考:
在發布的頁面上選擇橢圓(...)並選擇Manage Azure App Service settings 。 圖片供參考:
單擊“應用程序”頁面中的“添加設置”並添加設置名稱。 圖片供參考:
在 sql_connection 中,在遠程部分的本地部分中輸入 sql db 的連接字符串,單擊從本地插入值。 圖片供參考:
在項目的管理 Nuget 包中安裝 System.Data.SqlClient 包。 我添加了以下連接到 SQL 數據庫的代碼:
using System.Data.SqlClient;
using System.Threading.Tasks;
[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
// Get the connection string from app settings and use it to create a connection.
var str = Environment.GetEnvironmentVariable("sqldb_connection");
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "UPDATE SalesLT.SalesOrderHeader " +
"SET [Status] = 5 WHERE ShipDate < GetDate();";
using (SqlCommand cmd = new SqlCommand(text, conn))
{
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
以上函數每 15 秒運行一次,以根據發貨日期更新Status
列。
我在數據庫防火牆設置中添加了我的 IP 地址。 圖片供參考:
啟動后 15 秒,函數運行。 SalesOrderHeader 表中更新行數的輸出:
通過這種方式,我將 SQL 數據庫連接到我的函數應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.