跳過到頁腳內容
.NET幫助

Npgsql C#(對於開發者的運行原理)

Npgsql is a key technology that enables smooth communication between .NET applications and PostgreSQL 資料庫之間,提供順暢的溝通。 適用於 PostgreSQL 伺服器的 .NET 數據提供程式,即 Npgsql,是數據庫連接領域中創造力、效能和適應性的象徵。 它允許 C#、Visual Basic 和 F# 使用者訪問資料庫。 針對 EF Core 用戶還提供了一個傳統實體框架 6.x。

名為 IronPDF 的一個受歡迎的 .NET 庫,用於 C# 和 VB.NET 程式,來生成、修改和顯示 PDF 文件。 除了執行如合併多個 PDF、添加水印和從現有 PDF 文件中提取文字或圖像等複雜功能外,它還允許開發人員從多種來源(包括 HTML、照片和原始文字)創建 PDF 文件。

You will learn how to integrate IronPDF and NPGSQL in a C# application by following this tutorial. 我們將研究這些工具如何結合使用以改善應用程式的功能,從簡單的設置到複雜的功能。

如何使用 Npgsql

  1. 創建一個新的 C# 專案
  2. 安裝 Npgsql 庫。
  3. 連接到 Npgsql 資料庫。
  4. 執行查詢並獲取結果。
  5. 處理結果並關閉連接。

1. Npgsql 介紹

從根本上來說,Npgsql 充當 .NET 開發者與 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。 此庫提供了將 PostgreSQL 數據庫與 Npgsql 整合到專案中所需的工具和程式庫。

Npgsql C#(開發者如何運作):圖1 - 使用 NuGet 封裝管理器的解決方案管理,通過在 NuGet 封裝管理器的搜索欄中搜尋 Npgsql,然後選擇專案並點擊安裝按鈕來安裝 Npgsql。

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

幾個 C# 應用程式類型,如 Windows 表單(WinForms)和 Windows 控制台,可以使用 Npgsql。 雖然每個框架的實現方式不同,但基本概念始終相同:Npgsql 作為應用程式中數據庫的容器。

1.2.3 一個從 Npgsql 獲取數據的基本範例

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

using Npgsql;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // PostgreSQL connection string
        string connString = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase";

        // Create connection object
        using (var conn = new NpgsqlConnection(connString))
        {
            // Open the connection
            await conn.OpenAsync();

            // SQL query to execute
            string sql = "SELECT * FROM myTable";

            // Create NpgsqlCommand
            using (var cmd = new NpgsqlCommand(sql, conn))
            {
                // Execute the command and retrieve data
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    // 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"]);
                        // Output retrieved data to console
                        Console.WriteLine($"Name: {name}, Age: {age}");
                    }
                }
            }
            // Connection will be automatically closed here due to the 'using' block
        }
    }
}
using Npgsql;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // PostgreSQL connection string
        string connString = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase";

        // Create connection object
        using (var conn = new NpgsqlConnection(connString))
        {
            // Open the connection
            await conn.OpenAsync();

            // SQL query to execute
            string sql = "SELECT * FROM myTable";

            // Create NpgsqlCommand
            using (var cmd = new NpgsqlCommand(sql, conn))
            {
                // Execute the command and retrieve data
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    // 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"]);
                        // Output retrieved data to console
                        Console.WriteLine($"Name: {name}, Age: {age}");
                    }
                }
            }
            // Connection will be automatically closed here due to the 'using' block
        }
    }
}
Imports Npgsql
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' PostgreSQL connection string
		Dim connString As String = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase"

		' Create connection object
		Using conn = New NpgsqlConnection(connString)
			' Open the connection
			Await conn.OpenAsync()

			' SQL query to execute
			Dim sql As String = "SELECT * FROM myTable"

			' Create NpgsqlCommand
			Using cmd = New NpgsqlCommand(sql, conn)
				' Execute the command and retrieve data
				Using reader = Await cmd.ExecuteReaderAsync()
					' 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"))
						' Output retrieved data to console
						Console.WriteLine($"Name: {name}, Age: {age}")
					Loop
				End Using
			End Using
			' Connection will be automatically closed here due to the 'using' block
		End Using
	End Function
End Class
$vbLabelText   $csharpLabel

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

Npgsql C#(開發者如何運作):圖2 - 控制台輸出顯示從 PostgreSQL 數據庫獲取的名稱和年齡,使用.NET項目的 Npgsql 封裝。

2. Npgsql 與 PostgreSQL 的操作

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)
$vbLabelText   $csharpLabel

這段基本的代碼片段幫助我們連接到 PostgreSQL 資料庫伺服器。

3. 將 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 封裝,選擇它,然後按下 '安裝' 按鈕。 Visual Studio 將自動處理下載和安裝。

Npgsql C#(開發者如何運作):圖3 - 使用管理 NuGet 包封述工具來安裝 IronPDF,通過在 NuGet 包管理器的搜尋欄中搜尋'IronPdf',然後選擇項目並點擊安裝按鈕。

  • NuGet 會下載並安裝所需的依賴庫來支持您的專案。
  • 安裝完畢後,您可以在項目中開始使用 IronPDF。

通過 NuGet 網站安裝

要獲取有關 IronPDF 的更多信息,包括功能、兼容性和其他下載選項,請訪問 NuGet 上的 IronPDF 封裝網頁

使用 DLL 安裝

作為替代方法,您可以使用 IronPDF 的 DLL 文件直接整合到您的项目中。 使用此 IronPDF ZIP 封裝 連結來下載包含 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;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // StringBuilder for HTML content
        StringBuilder sb = new StringBuilder();
        var Renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer

        sb.Append("<h1>Dynamic PDF Generated from PostgreSQL Data</h1>");

        // PostgreSQL connection setup
        string connString = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase";

        using (var conn = new NpgsqlConnection(connString))
        {
            await conn.OpenAsync();

            string sql = "SELECT * FROM myTable";
            using (var cmd = new NpgsqlCommand(sql, conn))
            {
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    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>");
                    }
                }
            }

            // Generate and save the PDF document
            var pdf = Renderer.RenderHtmlAsPdf(sb.ToString());
            pdf.SaveAs("output.pdf");

            // Connection will be automatically closed here
        }

        Console.WriteLine("PDF generation completed. See output.pdf for results.");
    }
}
using Npgsql;
using IronPdf;
using System;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // StringBuilder for HTML content
        StringBuilder sb = new StringBuilder();
        var Renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer

        sb.Append("<h1>Dynamic PDF Generated from PostgreSQL Data</h1>");

        // PostgreSQL connection setup
        string connString = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase";

        using (var conn = new NpgsqlConnection(connString))
        {
            await conn.OpenAsync();

            string sql = "SELECT * FROM myTable";
            using (var cmd = new NpgsqlCommand(sql, conn))
            {
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    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>");
                    }
                }
            }

            // Generate and save the PDF document
            var pdf = Renderer.RenderHtmlAsPdf(sb.ToString());
            pdf.SaveAs("output.pdf");

            // Connection will be automatically closed here
        }

        Console.WriteLine("PDF generation completed. See output.pdf for results.");
    }
}
Imports Npgsql
Imports IronPdf
Imports System
Imports System.Text
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' StringBuilder for HTML content
		Dim sb As New StringBuilder()
		Dim Renderer = New ChromePdfRenderer() ' Instantiates Chrome Renderer

		sb.Append("<h1>Dynamic PDF Generated from PostgreSQL Data</h1>")

		' PostgreSQL connection setup
		Dim connString As String = "Host=myServerAddress;Port=myPort;Username=myUsername;Password=myPassword;Database=myDatabase"

		Using conn = New NpgsqlConnection(connString)
			Await conn.OpenAsync()

			Dim sql As String = "SELECT * FROM myTable"
			Using cmd = New NpgsqlCommand(sql, conn)
				Using reader = Await cmd.ExecuteReaderAsync()
					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
				End Using
			End Using

			' Generate and save the PDF document
			Dim pdf = Renderer.RenderHtmlAsPdf(sb.ToString())
			pdf.SaveAs("output.pdf")

			' Connection will be automatically closed here
		End Using

		Console.WriteLine("PDF generation completed. See output.pdf for results.")
	End Function
End Class
$vbLabelText   $csharpLabel

以下是上述代碼生成的結果。 欲了解有關 IronPDF 文檔 的更多資訊,請參考指南。

Npgsql C#(開發者如何運作):圖4 - 使用來自 Npgsql PostgreSQL 資料庫的數據和 IronPDF 產生的輸出 PDF。

結論

Through the great integration of IronPDF's PDF generation capabilities and Npgsql PostgreSQL database connectivity, developers may design adaptable and robust solutions for producing dynamic PDF documents that meet their unique needs.

$799 Lite 套件包含永久許可和一年的軟件支持選擇。 IronPDF 提供 免費許可選擇。 欲了解 Iron Software 的其他產品,請瀏覽其产品页面

IronPDF also offers comprehensive documentation and actively maintained code examples for PDF generation and manipulation to utilize the various features of IronPDF.

常見問題解答

如何將 C# 應用程序連接到 PostgreSQL 數據庫?

要將 C# 應用程序連接到 PostgreSQL 數據庫,您可以使用 Npgsql,它是 PostgreSQL 的 .NET 資料提供者。首先,通過 Visual Studio 中的 NuGet 套件管理器安裝 Npgsql。然後,創建一個連接字串並使用 NpgsqlConnection 類與數據庫建立連接。

Npgsql 在數據庫操作中的角色是什麼?

Npgsql 在數據庫操作中發揮著至關重要的作用,允許 .NET 應用程序與 PostgreSQL 數據庫進行通信。它支持多種功能,例如命令分批和異步 I/O,這些功能優化了性能,使其成為開發人員的首選。

參數化查詢如何提高 PostgreSQL 的安全性?

參數化查詢通過防止 SQL 注入攻擊來提高安全性。它們確保用戶輸入被視為數據而不是可執行代碼。使用 Npgsql,您可以使用參數化查詢來安全地處理 PostgreSQL 中的動態 SQL 查詢。

如何在 Windows Forms 應用程序中使用 Npgsql?

Npgsql 可以用於 Windows Forms 應用程序中來管理 PostgreSQL 數據庫。通過集成 Npgsql,開發人員可以在應用程序中執行查詢和檢索數據。可以使用 IronPDF 生成從 Windows Forms 應用程序中檢索的數據的 PDF。

Npgsql 為 .NET 開發人員提供了哪些好處?

Npgsql 提供全面的 PostgreSQL 支持,包括處理數組和 JSONB 以及異步 I/O 和命令分批等性能功能。這使得 Npgsql 成為 .NET 開發人員使用 PostgreSQL 數據庫的強大工具。

如何從C#中的PostgreSQL數據生成PDF報告?

您可以使用 IronPDF 從 PostgreSQL 數據中生成 PDF 報告。首先,使用 Npgsql 從 PostgreSQL 數據庫查詢和檢索數據。然後,根據需要格式化數據並使用 IronPDF 將其轉換為 PDF 文檔。

設置 Npgsql 在 C# 項目中包含哪些步驟?

要在 C# 項目中設置 Npgsql,首先使用 NuGet Package Manager 安裝 Npgsql。接下來,為您的 PostgreSQL 數據庫創建一個連接字串。使用 NpgsqlConnection 類連接到數據庫,並根據需要執行查詢。

如何將數據庫查詢結果記錄為 PDF 格式?

要將數據庫查詢結果記錄為 PDF 格式,使用 Npgsql 從 PostgreSQL 數據庫執行和檢索查詢結果。然後,使用 IronPDF 將數據轉換為格式良好的 PDF 文檔,可以根據需要保存或共享。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。