Npgsql C#(對於開發者的運行原理)
Npgsql 是一項關鍵技術,能夠實現 .NET 應用程式與 PostgreSQL 資料庫之間的順暢通信,因為開發人員尋找與資料庫協作的強大方式。 .NET 的 PostgreSQL 伺服器資料提供者,或稱 Npgsql,是資料庫連接領域中創意、有效性和適應性的象徵。 它允許 C#、Visual Basic 和 F# 使用者存取資料庫。 EF Core 使用者也可獲得傳統的Entity Framework 6.x。
一個受歡迎的 .NET 程式庫,稱為 IronPDF,在 C# 和 VB.NET 程式中用於生成、修改和顯示 PDF 文件。 除了執行如合併多個 PDF、新增浮水印和從現有 PDF 文件提取文字或圖像等複雜任務之外,它還允許開發人員從多個來源(包括 HTML、圖片和原始文字)建立 PDF 文件。
通過此教學,您將學習如何在 C# 應用程式中整合 IronPDF 和 NPGSQL。 我們將探討這些工具可以如何結合使用以改善您的應用程式的功能,從簡單的設置到複雜的功能。
如何使用 Npgsql
- 建立新的 C# 專案
- 安裝 Npgsql 程式庫。
- 連接到 Npgsql 資料庫。
- 執行查詢並獲取結果。
- 處理結果並關閉連接。
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 需要使用微軟的 .NET 套件管理工具,NuGet。 此程式庫提供了整合 PostgreSQL 資料庫與 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;
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 ClassImports 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在上述程式碼片段中,我們從 Npgsql 獲取資料並在控制台中顯示。 下面的圖片顯示了已執行查詢的結果。

2. 使用 PostgreSQL 的 Npgsql 操作
2.1 使用 PostgreSQL 的參數化查詢
因為參數化查詢使資料庫伺服器能夠快取查詢計畫,它們提高查詢效能並幫助防止 SQL 注入攻擊。 Npgsql 支援參數化查詢。 此外,使用參數化查詢可以更安全、更有效地處理動態 SQL 查詢。
2.2 使用 PostgreSQL 的批量操作
當處理大量資料集時,Npgsql 支援的批量插入、更新和刪除操作可以顯著提高速度。 由於批量操作,當可以在單個資料庫事務中處理多行時,與資料庫伺服器的單獨往返開銷減少。
使用 PostgreSQL 的事務
Npgsql 支援事務,這允許將多個資料庫操作分組為一個原子單元。 事務通過將所有更改提交到資料庫或在發生錯誤時回滾整個事務來提供資料一致性和完整性。
2.3 與 PostgreSQL 優化效能
Npgsql 在與 PostgreSQL 資料庫協作時提供了一些效能提升措施,包括查詢計畫快取、結果串流和命令批次處理,以減少延遲並提高吞吐量。 這些增強措施改善了應用程式的擴展性和整體速度。
2.4 與 PostgreSQL 資料庫的連接
在下述程式碼中,借助 Npgsql,可以輕鬆地連接到 PostgreSQL 資料庫伺服器。
NpgsqlConnection conn = new NpgsqlConnection(connString);NpgsqlConnection conn = new NpgsqlConnection(connString);Dim conn As New NpgsqlConnection(connString)Dim conn As New NpgsqlConnection(connString)此基本程式碼片段幫助我們連接到 PostgreSQL 資料庫伺服器。
3. 將 Npgsql 和 IronPDF 整合
3.1 一同使用 Npgsql 和 IronPDF
當 Npgsql 和 IronPDF 一同在 C# 專案中使用時,會出現令人興奮的可能性。 雖然 Npgsql 是處理 PostgreSQL 的一個很好的工具,IronPDF 則是將此內容轉換為 PDF 的一個絕佳工具。 由於這種連接性,程式員可以設計具有與資料庫通信並能夠將內容轉換為 PDF 功能的應用程式。
3.2 使用 IronPDF 獲取 PostgreSQL 的資料
使用者可以通過構建使用 Npgsql 的 Windows 控制台應用程式來在您的應用程式內與資料庫進行互動。 首先,在應用程式中新增資料庫存取。控制台上應有足夠的空間進行此控制,為 DB 互動留出充足的空間。 還包括資料型別映射和批量操作。
安裝IronPDF
-
在 Visual Studio 中啟動專案。
-
選擇"工具">"NuGet攜帶管理員">"攜帶管理員控制台"。
-
在套件管理器控制台中輸入以下命令並按下 Enter:
-
-
另外,您也可以使用解決方案的 NuGet 套件管理器來安裝 IronPDF。
- 在搜尋結果中找到 IronPDF 套件,選擇它,然後點擊"安裝"按鈕。 Visual Studio 將自動處理下載和安裝。

- NuGet 將會下載和安裝 IronPDF 套件以及您的專案所需的任何依賴項。
- 安裝完成後,您可以開始在您的專案中使用 IronPDF。
通過NuGet網站安裝
欲了解有關 IronPDF 的更多資訊,包括功能、相容性和其他下載選擇,請存取 NuGet 上的 IronPDF 套件網站。
使用DLL安裝
作為替代,您可以使用IronPDF的DLL文件將其直接整合到您的專案中。 使用此 IronPDF ZIP 套件 連結下載包含 DLL 的 ZIP 文件。 解壓縮後,把 DLL 新增到你的專案中。
實現邏輯
當我們開始運行應用程式時,它將使用 Npgsql .NET 程式庫從資料庫中提取資料。 借助 IronPDF,我們可以將資料庫內容轉換為 PDF 文件。
- 獲取資料:使用者開始轉換時,從 Npgsql .NET 提供者獲取最新內容。
- 使用 IronPDF 生成 PDF:使用 IronPDF 將 Npgsql 資料庫中的資料轉換為 PDF。 HtmlToPdf 類可以將 HTML 字串格式化為 PDF 文件。
- 儲存 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 ClassImports 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下面是上述程式碼生成的結果。 如需了解更多關於 IronPDF 文件的資訊,請參考該指南。

結論
通過 IronPDF 的 PDF 生成能力與 Npgsql PostgreSQL 資料庫連接性的良好整合,開發人員可以設計出適應性強且穩健的解決方案,以生成功能豐富、滿足其特定需求的動態 PDF 文件。
$999 Lite 套件除了包括永久授權和一年的軟體支持外,還包括升級選擇。 IronPDF 提供免費授權選項。 欲了解 Iron Software 的其他產品,請探索他們的產品頁面。
IronPDF 還提供全面的文件 和積極維護的PDF 生成和操作的程式碼範例,以利用 IronPDF 的各種功能。
Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。