C# PostgreSQL(對於開發者的運行原理)
歡迎來到本教學,本教學專為有興趣將 C# 應用程式與 PostgreSQL 整合的初學者所設計。 PostgreSQL 是全球使用最多的關聯式資料庫之一,以其可靠性和與包括 C# 在內的大量程式設計環境的相容性而聞名。 本指南將教您如何將 C# 應用程式連接到 PostgreSQL 資料庫、執行 SQL 語句查詢以及處理資料的基本知識。 我們將使用 Visual Studio、NuGet Package Manager 和 Npgsql 資料提供者等工具來建立一個與 PostgreSQL 伺服器通訊的簡單專案。 我們也將學習 IronPDF 函式庫與 PostgreSQL 的整合。
設定您的環境。
在開始編碼之前,請確保您的電腦已安裝 Visual Studio。 Visual Studio 是一種常用的整合開發環境 (IDE),支援 C# 及其他程式語言。 若要管理資料庫,請在本機安裝 PostgreSQL,或在 Azure 資料庫等雲端環境中架設 PostgreSQL 資料庫。
設定好 Visual Studio 和您的 PostgreSQL 伺服器後,建立一個新的 C# 專案。 您可以開啟 Visual Studio,進入"檔案"功能表,選擇"新增",然後選擇"專案"。 選擇 Console App (.NET Core) 作為專案類型,以保持簡單。
將 PostgreSQL 與 C# 整合
要將您的 C# 應用程式連接到 PostgreSQL 資料庫,您需要 Npgsql 資料提供者。 Npgsql 可作為 C# 應用程式與 PostgreSQL 資料庫之間的橋梁,讓您的程式碼能夠執行 SQL 指令並管理資料。
安裝 Npgsql。
在 Visual Studio 中開啟您新建立的專案。 在"解決方案總管"中的專案上按滑鼠右鍵,選擇"管理 NuGet 套件",然後搜尋 Npgsql 套件。 按一下套件名稱旁的安裝按鈕來安裝。 此動作可將 Npgsql 資料提供者新增至您的專案,讓您的應用程式與 PostgreSQL 進行通訊。 您也可以使用套件管理員控制台進行安裝。

設定資料庫連線
從 C# 與 PostgreSQL 資料庫互動的第一步是建立連線。 這需要連線字串,其中包括伺服器名稱、連接埠、使用者名稱和密碼等詳細資訊。 以下是 PostgreSQL 連接字串的基本範本:
string connectionString = "Host=localhost; Port=5432; Username=postgres; Password=yourpassword; Database=mydatabase";
string connectionString = "Host=localhost; Port=5432; Username=postgres; Password=yourpassword; Database=mydatabase";
Dim connectionString As String = "Host=localhost; Port=5432; Username=postgres; Password=yourpassword; Database=mydatabase"
將 localhost、yourpassword 和 mydatabase替換為您 PostgreSQL 伺服器的詳細資訊。
定義員工模型
我們定義了一個 Employee 實體模型,它將代表 PostgreSQL 資料庫中的資料。 此模型包含與資料庫表中欄位對應的屬性。
public class Employee
{
public int Id { get; set; } // Automatically becomes the primary key
public string LastName { get; set; }
}
public class Employee
{
public int Id { get; set; } // Automatically becomes the primary key
public string LastName { get; set; }
}
Public Class Employee
Public Property Id() As Integer ' - Automatically becomes the primary key
Public Property LastName() As String
End Class
此程式碼片段定義了一個簡單的 Employee 類別,該類別具有兩個屬性:Id 和 LastName。 Entity Framework Core 使用慣例推斷 Id 序列主鍵屬性應被視為主鍵。
設定應用程式的 DbContext。
AppDbContext 類別從 Entity Framework Core 延伸出 DbContext,作為 C# 應用程式與 PostgreSQL 資料庫之間的橋梁。 它包括配置細節,例如連接字串和代表資料庫中資料表的 DbSet 屬性。
public class AppDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; } // Represents the Employees table
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString = "Host=localhost; Port=5432; Username=postgres; Password=your_password; Database=your_database";
optionsBuilder.UseNpgsql(connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().ToTable("Employees");
}
}
public class AppDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; } // Represents the Employees table
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString = "Host=localhost; Port=5432; Username=postgres; Password=your_password; Database=your_database";
optionsBuilder.UseNpgsql(connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().ToTable("Employees");
}
}
Public Class AppDbContext
Inherits DbContext
Public Property Employees() As DbSet(Of Employee) ' - Represents the Employees table
Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
Dim connectionString As String = "Host=localhost; Port=5432; Username=postgres; Password=your_password; Database=your_database"
optionsBuilder.UseNpgsql(connectionString)
End Sub
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As ModelBuilder)
modelBuilder.Entity(Of Employee)().ToTable("Employees")
End Sub
End Class
-
DbSet 屬性:**公共資料庫集
員工 { get; set; } 宣告一組 Employee** 實體,這些實體對應到 PostgreSQL 資料庫中的 employee 資料表。 -
OnConfiguring 方法:此方法使用必要的資料庫連接字串配置DbContext 。 將 your_password 和 your_database 替換為您實際的 PostgreSQL 伺服器詳細資訊。
- OnModelCreating 方法:您可以在此使用 Fluent API 進一步配置實體行為。 在這個範例中,我們明確指定了資料表名稱,不過如果資料表名稱與 DbSet 屬性名稱相符,則可以選擇不指定資料表名稱。
主要程式邏輯
在 Program 類的 Main 方法中,我們會確保資料庫已建立,如果資料庫為空,則會為其加入初始資料種子,然後執行查詢以擷取和顯示員工資料。
class Program
{
static void Main(string[] args)
{
using (var context = new AppDbContext())
{
context.Database.EnsureCreated(); // Ensure the database and schema are created
if (!context.Employees.Any()) // Check if the Employees table is empty
{
context.Employees.Add(new Employee { LastName = "Software" });
context.SaveChanges(); // Save changes to the database
}
var employees = context.Employees.Where(e => e.LastName == "Software").ToList();
foreach (var employee in employees)
{
Console.WriteLine($"Employee ID: {employee.Id}, Last Name: {employee.LastName}");
}
}
}
}
class Program
{
static void Main(string[] args)
{
using (var context = new AppDbContext())
{
context.Database.EnsureCreated(); // Ensure the database and schema are created
if (!context.Employees.Any()) // Check if the Employees table is empty
{
context.Employees.Add(new Employee { LastName = "Software" });
context.SaveChanges(); // Save changes to the database
}
var employees = context.Employees.Where(e => e.LastName == "Software").ToList();
foreach (var employee in employees)
{
Console.WriteLine($"Employee ID: {employee.Id}, Last Name: {employee.LastName}");
}
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
Using context = New AppDbContext()
context.Database.EnsureCreated() ' Ensure the database and schema are created
If Not context.Employees.Any() Then ' Check if the Employees table is empty
context.Employees.Add(New Employee With {.LastName = "Software"})
context.SaveChanges() ' Save changes to the database
End If
Dim employees = context.Employees.Where(Function(e) e.LastName = "Software").ToList()
For Each employee In employees
Console.WriteLine($"Employee ID: {employee.Id}, Last Name: {employee.LastName}")
Next employee
End Using
End Sub
End Class
上述程式碼會檢查資料庫是否存在,如果不存在,則會建立資料庫及模式。 這是一種在開發過程中直接啟動新資料庫的方式。 此 SQL 語句會檢查,如果 Employees 表為空,程式會新增一位姓氏為"Software"的 Employee 並將變更儲存至資料庫。 該程式會查詢 Employees 表中姓氏為"Software"的條目,並將其詳細資訊列印到控制台。
輸出
以下是執行程式時的控制台輸出:

而且是 PgAdmin 中的表格資料:

IronPDF 簡介
探索 IronPDF 函式庫功能,瞭解這個適用於 C# 的綜合函式庫如何讓開發人員在 .NET 應用程式中建立、編輯和處理 PDF 文件。 這個功能強大的工具簡化了 從 HTML、URL 和圖片產生 PDF 的過程。 它還能提供基本的 PDF 操作,例如編輯文字和圖片,以及新增加密和數位簽章等安全功能。 IronPDF 以其易用性脫穎而出,讓開發人員可以用最少的代碼實現複雜的 PDF 功能。
IronPDF 提供將 HTML毫不費力地轉換為 PDF 的功能,同時保持版面和樣式不變。 此功能非常適合從網頁內容(如報告、發票和文件)產生 PDF。 它可將 HTML 檔案、URL 和 HTML 字串轉換成 PDF 檔案。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
將 IronPDF 與 PostgreSQL 資料庫整合,在需要根據資料庫中儲存的動態資料產生 PDF 報告或文件的情況下,可以發揮極大的作用。 這包括直接從 PostgreSQL 資料庫中的資料產生發票、報告、客戶結單等。
安裝 IronPDF。
在使用 IronPDF 之前,您必須先將其加入專案中。 這可透過 NuGet Package Manager 輕鬆完成:
Install-Package IronPdf
從 PostgreSQL 資料產生 PDF。
在這個範例中,讓我們產生一份簡單的 PDF 報告,列出 PostgreSQL 資料庫中的員工。 我們假設您已依照前幾節所述設定了 AppDbContext 和 Employee 模型。
首先,確保您的專案已安裝 IronPDF 函式庫。 然後,您可以使用下列程式碼從 PostgreSQL 資料庫取得資料,並產生 PDF 報告:
class Program
{
static void Main(string[] args)
{
IronPdf.License.LicenseKey = "Key";
// Initialize the database context
using (var context = new AppDbContext())
{
// Fetch employees from the database
var employees = context.Employees.ToList();
// Generate HTML content for the PDF
var htmlContent = "<h1>Employee Report</h1>";
htmlContent += "<table><tr><th>ID</th><th>Last Name</th></tr>";
foreach (var employee in employees)
{
htmlContent += $"<tr><td>{employee.Id}</td><td>{employee.LastName}</td></tr>";
}
htmlContent += "</table>";
// Instantiate the IronPDF HtmlToPdf converter
var renderer = new ChromePdfRenderer();
// Generate the PDF document from the HTML content
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the generated PDF to a file
var outputPath = "f:\\EmployeeReport.pdf";
pdf.SaveAs(outputPath);
Console.WriteLine($"PDF report generated: {outputPath}");
}
}
}
class Program
{
static void Main(string[] args)
{
IronPdf.License.LicenseKey = "Key";
// Initialize the database context
using (var context = new AppDbContext())
{
// Fetch employees from the database
var employees = context.Employees.ToList();
// Generate HTML content for the PDF
var htmlContent = "<h1>Employee Report</h1>";
htmlContent += "<table><tr><th>ID</th><th>Last Name</th></tr>";
foreach (var employee in employees)
{
htmlContent += $"<tr><td>{employee.Id}</td><td>{employee.LastName}</td></tr>";
}
htmlContent += "</table>";
// Instantiate the IronPDF HtmlToPdf converter
var renderer = new ChromePdfRenderer();
// Generate the PDF document from the HTML content
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the generated PDF to a file
var outputPath = "f:\\EmployeeReport.pdf";
pdf.SaveAs(outputPath);
Console.WriteLine($"PDF report generated: {outputPath}");
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
IronPdf.License.LicenseKey = "Key"
' Initialize the database context
Using context = New AppDbContext()
' Fetch employees from the database
Dim employees = context.Employees.ToList()
' Generate HTML content for the PDF
Dim htmlContent = "<h1>Employee Report</h1>"
htmlContent &= "<table><tr><th>ID</th><th>Last Name</th></tr>"
For Each employee In employees
htmlContent &= $"<tr><td>{employee.Id}</td><td>{employee.LastName}</td></tr>"
Next employee
htmlContent &= "</table>"
' Instantiate the IronPDF HtmlToPdf converter
Dim renderer = New ChromePdfRenderer()
' Generate the PDF document from the HTML content
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Save the generated PDF to a file
Dim outputPath = "f:\EmployeeReport.pdf"
pdf.SaveAs(outputPath)
Console.WriteLine($"PDF report generated: {outputPath}")
End Using
End Sub
End Class
輸出
當您執行程式碼時,會顯示此控制台輸出:

本 PDF 已生成:

結論
您剛剛使用 C# 和 PostgreSQL 踏入資料庫管理的世界,邁出了重要的第一步。 依照本教學的指示,您已學會如何在 Visual Studio 中建立專案、安裝必要的套件,以及執行基本的資料庫操作。 當您愈來愈熟悉這些概念時,您會發現 C# 與最重要的關聯式資料庫系統之一結合的力量與彈性。 不斷嘗試不同的查詢和實體配置,以加深您對 C# 如何與 PostgreSQL 互動的了解。
IronPDF 提供 免費試用 IronPDF 功能,讓開發人員無需任何初始投資即可探索其特色和功能。 此試用版特別適用於評估 IronPDF 在 .NET 應用程式中產生、編輯和轉換 PDF 文件時,是否符合您專案的需求。 試用期結束後或生產使用時,必須取得授權。 IronPDF 的許可價格從 $799 起,提供一系列功能和支援選項,以滿足不同的開發需求。
常見問題解答
如何將C#應用程式連接到PostgreSQL資料庫?
要將C#應用程式連接到PostgreSQL資料庫,您需要使用Npgsql資料提供程序,可以通過Visual Studio中的NuGet包管理器安裝它。您還需要一個正確配置的連接字串,其中包括服務器名稱、端口、用戶名、密碼和資料庫名稱。
設置一個帶有PostgreSQL的C#項目涉及哪些步驟?
首先,在您的機器上安裝Visual Studio和PostgreSQL。然後,創建一個新的C#項目,並使用NuGet包管理器安裝Npgsql資料提供程序。配置您的連接字串,並確保您的PostgreSQL服務器正在運行。
如何在C#應用程式中執行SQL命令?
您可以使用Npgsql資料提供程序在C#應用程式中執行SQL命令。建立與PostgreSQL資料庫的連接後,您可以使用NpgsqlCommand來運行如SELECT、INSERT、UPDATE和DELETE的SQL查詢。
如何從C#中的PostgreSQL資料生成PDF報告?
IronPDF允許您從C#中的PostgreSQL資料生成PDF報告。您可以從資料庫中檢索資料,並使用IronPDF的功能創建PDF文檔,包括將HTML內容轉換為PDF或編輯現有的PDF。
在C#中使用Npgsql資料提供程序的目的何在?
Npgsql資料提供程序在C#中用於促進與PostgreSQL資料庫的通信。它允許您的應用程式執行SQL查詢、管理資料並無縫地與資料庫進行交互。
如何使用C#創建並初始化一個資料庫?
在C#中,您可以使用context.Database.EnsureCreated()方法創建資料庫,該方法會檢查資料庫是否存在,如果不存在則創建。您可以通過向上下文添加資料並使用context.SaveChanges()來保存它來初始化資料。
在.NET應用程式中使用IronPDF有什麼好處?
IronPDF在.NET應用程式中是有益的,因為它提供了創建、編輯和操作PDF文檔的強大功能。它支持將HTML轉換為PDF,編輯文本和圖像,並添加如加密等安全功能。
如何在C#中為PostgreSQL表定義資料模型?
您可以通過創建一個類來定義C#中的資料模型,該類對應於您的PostgreSQL表結構。類中的每個屬性應該與表中的一列匹配,從而允許Entity Framework正確映射資料。
如何排除C#與PostgreSQL之間的連接問題?
要排除連接問題,確保您的連接字串配置正確,確保您的PostgreSQL服務器正在運行,並檢查是否有任何防火牆或網路問題可能阻止了連接。



