在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
歡迎來到這個針對初學者設計的教程,適合有興趣將C#應用程式整合PostgreSQL. PostgreSQL 是全球使用最廣泛的關聯式數據庫之一,以其可靠性和與眾多編程環境(包括 C#)的兼容性而聞名。 本指南將引導您瞭解將 C# 應用程式連接到 PostgreSQL 資料庫、執行 SQL 語句查詢及處理資料的基礎。 我們將使用 Visual Studio、NuGet 套件管理器和 Npgsql 資料提供者來創建一個與 PostgreSQL 伺服器通信的簡單專案。 我們還將學習如何將IronPDF程式庫與PostgreSQL整合。
在開始編寫程式碼之前,請確保您的電腦已安裝 Visual Studio。 Visual Studio 是一個受歡迎的集成開發環境(集成開發環境)支援 C# 及其他程式語言。 要進行資料庫管理,請在本地機器上安裝PostgreSQL,或在像Azure Database這樣的雲端環境中設置PostgreSQL資料庫。
在設定好 Visual Studio 和您的 PostgreSQL 伺服器後,創建一個新的 C# 專案。 您可以透過開啟 Visual Studio、進入檔案選單、選擇新增,然後選擇專案來完成此操作。 選擇主控台應用程式(.NET Core)選擇您的專案類型以保持簡單。
要將您的 C# 應用程式連接到 PostgreSQL 資料庫,您需要 Npgsql 資料提供者。 Npgsql 是 C# 應用程式與 PostgreSQL 資料庫之間的橋樑,使您的程式碼能夠執行 SQL 命令及管理資料。
在 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 序列主鍵屬性應被視作主鍵。
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 屬性:public DbSet
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();
if (!context.Employees.Any())
{
context.Employees.Add(new Employee { LastName = "Software" });
context.SaveChanges();
}
var employees = context.Employees.Where(e => e.LastName == "Doe").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();
if (!context.Employees.Any())
{
context.Employees.Add(new Employee { LastName = "Software" });
context.SaveChanges();
}
var employees = context.Employees.Where(e => e.LastName == "Doe").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()
If Not context.Employees.Any() Then
context.Employees.Add(New Employee With {.LastName = "Software"})
context.SaveChanges()
End If
Dim employees = context.Employees.Where(Function(e) e.LastName = "Doe").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」的條目,並將其詳細資訊輸出到控制台。 我們可以在 Postgres 資料庫中加入一個 SQL 查詢以刪除表格。 我們也可以為我們的資料庫添加 .NET 數據提供者。
以下是執行程式時的控制台輸出:
這是 PgAdmin 中的表格數據:
探索 IronPDF 程式庫的功能了解這個用於 C# 的綜合程式庫如何使開發人員能夠在 .NET 應用程式中創建、編輯和操作 PDF 文件。 這個強大的工具簡化了從 HTML 生成 PDF、URL 和圖像。 它還提供基本的 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 之前,必須將其添加到您的專案中。 這可以通過 NuGet 套件管理器輕鬆完成:
Install-Package IronPdf
在此範例中,讓我們生成一個簡單的 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 的授權價格起始於 $749,提供一系列功能和支援選項,適合不同的開發需求。