.NET 幫助

Npgsql C#(開發人員如何使用)

發佈 2024年4月29日
分享:

Npgsql 是一項關鍵技術,能夠實現 .NET 應用程序與 之間的順暢通信 PostgreSQL 隨著開發人員尋找強大的方式與資料庫合作,資料庫變得越來越重要。適用於 PostgreSQL 伺服器的 .NET 資料提供者,或稱 Npgsql,在資料庫連接領域中是創意、有效性和適應性的象徵。它允許 C#、Visual Basic 和 F# 用戶存取資料庫。針對 EF 核心用戶,也提供了一個傳統的實體框架 6.x。

一個受歡迎的 .NET 程式庫叫 IronPDF 用於 C# 和 VB.NET 程式中生成、修改和顯示 PDF 文件。除了執行合併多個 PDF、添加水印以及從現有 PDF 文件中提取文字或圖片等複雜任務外,它還使開發者能夠從各種來源創建 PDF 文件,包括 HTML、圖片和原始文字。

您將學習如何整合 IronPDFNPGSQL 透過遵循本教程在C#應用程式中使用。我們將探討如何結合這些工具以改善應用程式的功能,從簡單的設置到複雜的功能。

如何使用 Npgsql

  1. 建立一個新的 C# 專案

  2. 安裝 Npgsql 庫。

  3. 連接到 Npgsql 資料庫。

  4. 執行查詢並獲取結果。

  5. 處理結果並關閉連接。

1. Npgsql 介紹

從本質上說, Npgsql 充當.NET開發者與PostgreSQL之間的連接,PostgreSQL 是一個以穩定性、可擴展性和擴充性著稱的開源關聯式資料庫管理系統。NPGSQL 通過提供豐富的功能集,使開發者能夠處理事務、進行查詢、檢索數據和簡化資料庫操作,並提供無與倫比的便利性和效率。

1.1 使用 Npgsql 的優點

性能: Npgsql 的速度和效率是內建的。為了保證在使用 PostgreSQL 資料庫時的最佳速度,它利用了像是批次命令、異步輸入/輸出和優化資料類型的功能。

完整的 PostgreSQL 支援: Npgsql 的目標是提供對所有 PostgreSQL 功能的完整支援,例如陣列、JSONB、進階資料類型和使用者定義類型。這意味著程式設計師可以在 .NET 應用程式中充分利用 PostgreSQL 的全部潛力。

1.2 開始使用 Npgsql

1.2.1 在 C# 專案中設定 Npgsql

將 Npgsql 併入 C# 專案很簡單。添加 Npgsql 需要使用 Microsoft 的 .NET 套件管理工具 NuGet。這個庫提供了將 Postgrey 數據庫和 Npgsql 集成到您的專案所需的工具和庫。

Npgsql C#(適用於開發人員的工作原理):圖1 - 使用解決方案的 NuGet 套件管理功能安裝 Npgsql,在 NuGet 套件管理器的搜尋欄位中搜尋 Npgsql,然後選擇專案並點擊安裝按鈕。

1.2.2 在 Windows 控制台和表單中實現 Npgsql

多種 C# 應用程式類型,例如 Windows Forms (WinForms) 和 Windows 控制台可以使用 Npgsql。雖然每個框架的實現不同,但基本思想總是相同的:Npgsql 在應用程式內作為數據庫的容器。

1.2.3 用 Npgsql 獲取數據的一個基本例子

在使用 PostgreSQL 資料庫前,先建立與 Npgsql 的連接。然後,運行 SQL 查詢從 PostgreSQL 獲取數據。NpgsqlCommand 是一個運行 SQL 查詢的工具。

using Npgsql;
using System.Text;
class Program
{
    static void Main(string [] args)
    {
        // PostgreSQL connection string
        string connString = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase";
        // Create connection object
        NpgsqlConnection conn = new NpgsqlConnection(connString);
        // Open the connection
        conn.Open();
        // SQL query
        string sql = "SELECT * FROM myTable";
        // Create NpgsqlCommand
        NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
        // Execute the command and retrieve data
        NpgsqlDataReader reader = cmd.ExecuteReader();
        // Loop through the retrieved data
        while (await reader.ReadAsync())
        {
            // Retrieve data from the data reader
            string name = reader ["Name"].ToString();
            int age = Convert.ToInt32(reader ["Age"]);
            // Add data to the PDF
            console.writeline($"Name: {name}, Age: {age}");
        }
        // Close the connection when done
        conn.Close();
    }
}
using Npgsql;
using System.Text;
class Program
{
    static void Main(string [] args)
    {
        // PostgreSQL connection string
        string connString = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase";
        // Create connection object
        NpgsqlConnection conn = new NpgsqlConnection(connString);
        // Open the connection
        conn.Open();
        // SQL query
        string sql = "SELECT * FROM myTable";
        // Create NpgsqlCommand
        NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
        // Execute the command and retrieve data
        NpgsqlDataReader reader = cmd.ExecuteReader();
        // Loop through the retrieved data
        while (await reader.ReadAsync())
        {
            // Retrieve data from the data reader
            string name = reader ["Name"].ToString();
            int age = Convert.ToInt32(reader ["Age"]);
            // Add data to the PDF
            console.writeline($"Name: {name}, Age: {age}");
        }
        // Close the connection when done
        conn.Close();
    }
}
Imports Npgsql
Imports System.Text
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' PostgreSQL connection string
		Dim connString As String = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase"
		' Create connection object
		Dim conn As New NpgsqlConnection(connString)
		' Open the connection
		conn.Open()
		' SQL query
		Dim sql As String = "SELECT * FROM myTable"
		' Create NpgsqlCommand
		Dim cmd As New NpgsqlCommand(sql, conn)
		' Execute the command and retrieve data
		Dim reader As NpgsqlDataReader = cmd.ExecuteReader()
		' Loop through the retrieved data
		Do While Await reader.ReadAsync()
			' Retrieve data from the data reader
			Dim name As String = reader ("Name").ToString()
			Dim age As Integer = Convert.ToInt32(reader ("Age"))
			' Add data to the PDF
			console.writeline($"Name: {name}, Age: {age}")
		Loop
		' Close the connection when done
		conn.Close()
	End Sub
End Class
VB   C#

在上面的程式碼片段中,我們從Npgsql獲取數據並在控制台中顯示。下圖顯示了執行查詢的結果。

Npgsql C#(開發人員的運作方式):圖2 - 使用 Npgsql 套件在 .NET 專案中從 PostgreSQL 數據庫顯示姓名和年齡的控制台輸出

2. 使用 PostgreSQL 進行 Npgsql 操作

2.1 使用 PostgreSQL 的參數化查詢

由於參數化查詢使資料庫伺服器能夠快取查詢計劃,它們提升了查詢效能並有助於防止 SQL 注入攻擊。Npgsql 支援參數化查詢。此外,參數化查詢還使得以安全和有效的方式處理動態 SQL 查詢更加容易。

2.2 與 PostgreSQL 的批量操作

在處理巨量資料集時,Npgsql 支援的批量插入、更新和刪除操作可以大大提高速度。當多行可以在單一資料庫交易中處理時,批量操作減少了與資料庫伺服器執行多次往返操作的負擔。

使用 PostgreSQL 的交易

Npgsql 支援交易,這使得可以將多個資料庫操作組成一個原子單位。交易透過要麼將所有更改提交到資料庫,要麼在出現錯誤時回滾整個交易,來提供資料一致性和完整性。

2.3 使用 PostgreSQL 的性能優化

在使用 PostgreSQL 資料庫時,Npgsql 提供了一系列的性能增強功能,包括查詢計劃緩存、結果串流和命令批處理,以減少延遲和增加吞吐量。這些增強功能提高了應用程式的可擴展性和整體速度。

2.4 與 PostgreSQL 資料庫的連接

可以透過 Npgsql 和下面幾行程式碼輕鬆連接 PostgreSQL 資料庫伺服器。

NpgsqlConnection conn = new NpgsqlConnection(connString);
NpgsqlConnection conn = new NpgsqlConnection(connString);
Dim conn As New NpgsqlConnection(connString)
VB   C#

此基本程式碼片段幫助我們連接到 PostgreSQL 資料庫伺服器。

將 Npgsql 與 IronPDF 整合

3.1 同時使用 Npgsql 和 IronPDF

當在 C# 專案中同時使用 Npgsql 和 IronPDF 時,會出現一些令人興奮的可能性。雖然 Npgsql 是處理 Postgresql 的一個很棒的工具,IronPDF 也是將這些內容轉換為 PDF 的一個很棒的工具。由於這種連接性,程式設計師可以設計能夠與資料庫通信並能夠將這些內容轉換為 PDF 的應用程式。

3.2 使用 IronPDF 獲取 Postgresql 數據

用戶可以通過構建使用 Npgsql 的 Windows 控制台應用程序來與應用程序內的數據庫交互。首先,將數據庫訪問添加到您的應用程序中。控制台應有足夠的空間來控制此操作,並留出充足的空間進行數據庫交互。還應包括數據類型映射和批量操作。

安裝 IronPDF

  • 在 Visual Studio 中啟動專案。
  • 選擇 "工具" > "NuGet 套件管理員" > "套件管理員主控台"。

    • 在套件管理員主控台中輸入以下指令並按 Enter:
Install-Package IronPdf
  • 另外,你也可以使用 NuGet 套件管理器來安裝 IronPDF。

    • 在搜索結果中找到 IronPDF 套件,選擇它,然後點擊「Install」按鈕。Visual Studio 將自動處理下載和安裝。

Npgsql C#(對開發人員的運作方式):圖 3 - 通過在 NuGet 包管理器的搜索欄中搜索 IronPdf,使用管理 NuGet 包為解決方案安裝 IronPDF,然後選擇項目並點擊安裝按鈕。

  • IronPDF 套件將通過 NuGet 下載並安裝,以及您的專案中所需的任何相依性。
  • 安裝後,您可以開始在您的專案中使用 IronPDF。

通過 NuGet 網站安裝

有關 IronPDF 的更多信息,包括功能、相容性和其他下載選擇,請訪問 NuGet 網站上的 IronPDF 頁面:https://www.nuget.org/packages/IronPdf

利用DLL安裝

作為替代方案,您可以使用IronPDF的dll文件將其直接整合到您的項目中。使用這個 連結 下載包含DLL的ZIP檔案。解壓縮後,將DLL添加到您的項目中。

實現邏輯

當我們開始運行應用程序時,它將使用 Npgsql .NET 庫從數據庫中獲取數據。借助 IronPDF,我們可以將數據庫內容轉換為 PDF 文檔。

  1. 獲取數據:當用戶開始轉換時,從 Npgsql .NET 提供者獲取最新內容。

  2. 使用 IronPDF 生成 PDF:使用 IronPDF 將 Npgsql 數據庫中的數據轉換為 PDF。可以使用 HtmlToPdf 類將 HTML 字符串格式化為 PDF 文檔。

  3. 保存 PDF 並通知:將生成的 PDF 保存到指定位置或在控制台上顯示消息。一旦 PDF 保存完成,請通過終端消息通知用戶轉換成功。
using Npgsql;
using IronPdf;
using System.Text;
class Program
{
    static void Main(string [] args)
    {
        StringBuilder sb = new StringBuilder();
        var Renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer
        sb.Append("<h1>Dynamic PDF Generated from PostgreSQL Data</h1>");
    //ngsql code here
        while (await reader .ReadAsync())
        {
            // Retrieve data from the data reader
            string name = reader ["Name"].ToString();
            int age = Convert.ToInt32(reader ["Age"]);
            // Add data to the PDF
            sb.Append($"<p>Name: {name}, Age: {age}</p>");
        }
        var pdf = Renderer.RenderHtmlAsPdf(sb.ToString());
        // Save the PDF document
        pdf.SaveAs("output.pdf");
        // Close the connection when done
        conn.Close();
    }
}
using Npgsql;
using IronPdf;
using System.Text;
class Program
{
    static void Main(string [] args)
    {
        StringBuilder sb = new StringBuilder();
        var Renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer
        sb.Append("<h1>Dynamic PDF Generated from PostgreSQL Data</h1>");
    //ngsql code here
        while (await reader .ReadAsync())
        {
            // Retrieve data from the data reader
            string name = reader ["Name"].ToString();
            int age = Convert.ToInt32(reader ["Age"]);
            // Add data to the PDF
            sb.Append($"<p>Name: {name}, Age: {age}</p>");
        }
        var pdf = Renderer.RenderHtmlAsPdf(sb.ToString());
        // Save the PDF document
        pdf.SaveAs("output.pdf");
        // Close the connection when done
        conn.Close();
    }
}
Imports Npgsql
Imports IronPdf
Imports System.Text
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim sb As New StringBuilder()
		Dim Renderer = New ChromePdfRenderer() ' Instantiates Chrome Renderer
		sb.Append("<h1>Dynamic PDF Generated from PostgreSQL Data</h1>")
	'ngsql code here
		Do While Await reader.ReadAsync()
			' Retrieve data from the data reader
			Dim name As String = reader ("Name").ToString()
			Dim age As Integer = Convert.ToInt32(reader ("Age"))
			' Add data to the PDF
			sb.Append($"<p>Name: {name}, Age: {age}</p>")
		Loop
		Dim pdf = Renderer.RenderHtmlAsPdf(sb.ToString())
		' Save the PDF document
		pdf.SaveAs("output.pdf")
		' Close the connection when done
		conn.Close()
	End Sub
End Class
VB   C#

以下是由上述程式碼生成的結果。如需了解更多 IronPDF 文檔,請參閱 這裡.

Npgsql C#(它如何為開發人員工作):圖4 - 使用Npgsql PostgreSQL數據庫中的數據和IronPDF生成的輸出PDF。

結論

通過卓越的整合 IronPDF的 PDF 生成功能和 NPGSQL PostgreSQL 數據庫連接,開發人員可以設計靈活和穩健的解決方案,生成滿足其獨特需求的動態 PDF 文檔。

$749 的 Lite 套裝包包括升級選項,還有永久許可和一年的軟件支持。IronPDF 提供 免費授權要了解更多 Iron Software 其他產品,請點擊這個 連結IronPDF 也提供完整的文件 指南 並積極維護 程式碼範例 如何利用IronPDF的各種功能來生成和編輯PDF。

< 上一頁
棱鏡日誌 (它對開發者的工作原理)
下一個 >
C# 部分 (開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >