
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 Database這樣的雲環境中建立一個PostgreSQL資料庫。
設定好Visual Studio和PostgreSQL伺服器後,建立一個新的C#專案。 您可以通過打開Visual Studio,進入文件選單,選擇新建,然後專案來做到這一點。 選擇Console App (.NET Core)作為您的專案型別以保持簡單。
Integrating PostgreSQL with 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";Dim connectionString As String = "Host=localhost; Port=5432; Username=postgres; Password=yourpassword; Database=mydatabase"用您的PostgreSQL伺服器詳細資料替換localhost,yourpassword,和mydatabase。
定義Employee模型
我們定義了一個Employee實體模型,將表示我們在PostgreSQL資料庫中的資料。 此模型包含與資料庫表中的列對應的屬性。
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
Inherits DbContext
Public Property Employees As DbSet(Of Employee) ' Represents the Employees table
Protected Overrides Sub OnConfiguring(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(modelBuilder As ModelBuilder)
modelBuilder.Entity(Of Employee)().ToTable("Employees")
End Sub
End Class-
DbSet Property: public
DbSet<Employee>Employees{ get; set; }宣告了一組Employee實體,這些實體映射到PostgreSQL資料庫中的employee表。 -
OnConfiguring方法:此方法使用必要的資料庫連接字串配置DbContext。 用您的實際PostgreSQL伺服器詳細資料替換your_password和your_database。
-
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}");
}
}
}
}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");
}
}Imports IronPdf
Module Program
Sub Main(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 Module將IronPDF與PostgreSQL資料庫相結合在需要根據儲存在資料庫中的動態資料生成PDF報告或文件的場景中非常有用。 這可能涵蓋從PostgreSQL資料庫中以直接生成發票、報告、客戶報表等範圍的用途。
安裝IronPDF
在使用IronPDF之前,您必須將其新增到您的專案中。 這可以通過NuGet Package Manager輕鬆完成:
從PostgreSQL資料生成PDF
在此範例中,我們將生成一份列出我們PostgreSQL資料庫中員工的簡單PDF報告。 我們假設您已經按照前面的章節中描述的設置好了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}");
}
}
}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如何滿足您專案中生成、編輯和轉換PDF文件的需求。 在試用期之後或用於生產用途時,則需要購買授權。 IronPDF的授權從$999開始,提供適合不同開發需求的特徵和支援選項。

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。
相關文章


