跳過到頁腳內容
.NET幫助

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

歡迎來到這個專為有興趣將 C# 應用程式與PostgreSQL整合的新手設計的教程。 PostgreSQL 是全球最常用的關聯資料庫之一,以其可靠性和與眾多程式設計環境(包括 C#)的相容性而聞名。 本指南將引導您了解如何將 C# 應用程式連接到 PostgreSQL 資料庫、執行 SQL 語句查詢以及處理資料的基本知識。 我們將使用像是 Visual Studio、NuGet 套件管理器和 Npgsql 資料提供者等工具來創建一個與 PostgreSQL 伺服器通信的簡單專案。 我們還將學習如何將 IronPDF 庫與 PostgreSQL 整合。

設置您的環境

在進入編碼之前,確保您的電腦上已安裝 Visual Studio。 Visual Studio 是一個流行的集成開發環境 (IDE),支持 C# 以及其他程式設計語言。 為了進行資料庫管理,在本地電腦上安裝 PostgreSQL,或在像是 Azure Database 的雲端環境中設置一個 PostgreSQL 資料庫。

在設置 Visual Studio 和您的 PostgreSQL 伺服器後,創建一個新的 C# 專案。 您可以通過打開 Visual Studio、轉到檔案選單、選擇新建,然後選擇專案來完成此操作。 選擇主控台應用程式 (.NET Core) 作為您的專案類型以保持簡單。

將 PostgreSQL 與 C# 整合

要將您的 C# 應用程式連接到 PostgreSQL 資料庫,您需要 Npgsql 資料提供者。 Npgsql 作為 C# 應用程式與 PostgreSQL 資料庫之間的橋樑,讓您的代碼能夠執行 SQL 命令並管理資料。

安裝 Npgsql

在 Visual Studio 中打開您新創建的專案。 在解決方案總管中右鍵點擊您的專案,選擇“管理 NuGet 包”,然後搜尋 Npgsql 套件。 點擊套件名稱旁邊的安裝按鈕進行安裝。 此操作會將 Npgsql 資料提供者添加到您的專案中,使您的應用程式能夠與 PostgreSQL 交流。 您也可以使用套件管理器控制台進行安裝。

! C# PostgreSQL (開發者如何工作):圖 1 - Npgsql

配置資料庫連接

從 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"
$vbLabelText   $csharpLabel

localhostyourpasswordmydatabase 替換為您的 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
$vbLabelText   $csharpLabel

這段代碼片段定義了一個簡單的 Employee 類,具有兩個屬性:IdLastName。 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
$vbLabelText   $csharpLabel
  • DbSet 屬性公共 DbSet Employees { get; set; } 宣告了一組 Employee 實體,這些實體對應於 PostgreSQL 資料庫中的員工表。

  • OnConfiguring 方法:這個方法使用必要的資料庫連接字串配置 DbContext。 將 your_passwordyour_database 替換為您實際的 PostgreSQL 伺服器詳細資訊。

  • OnModelCreating 方法:在這裡,您可以使用流暢的 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
$vbLabelText   $csharpLabel

上述代碼檢查資料庫是否存在,如不存在將建立資料庫和模式。 這是開發期間引導新資料庫的簡單方法。 這個 SQL 語句檢查,如果 Employees 表為空,程序將添加一個姓“Software”的新 Employee 並將變更保存到資料庫。 程序查詢 Employees 表中姓“Software”的條目並將其詳細資訊打印到控制台。

輸出

這是運行程序時的控制台輸出:

! C# PostgreSQL (開發者如何工作):圖 2 - 輸出

而 PgAdmin 中的表數據是:

! C# PostgreSQL (開發者如何工作):圖 3 - 表輸出

IronPDF 简介

探索 IronPDF 庫功能,了解這個全面的 C# 庫如何使開發人員能夠在 .NET 應用程式中創建、編輯和操作 PDF 文檔。 這個強大的工具簡化了從 HTML 生成 PDF、URL 和圖像的過程。 它還提供必要的 PDF 操作,例如編輯文本和圖像,以及添加安全功能,如加密和數字簽名。 IronPDF 以易用性著稱,讓開發人員能夠用最少的代碼實現複雜的 PDF 功能。

IronPDF 提供將HTML 輕鬆轉換為 PDF的功能,同時保持佈局和樣式不變。 這個功能非常適合從基於網頁的內容(如報告、發票和文檔)生成 PDF。 它將 HTML 文件、網址和 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
$vbLabelText   $csharpLabel

在需要基於資料庫中存儲的動態資料生成 PDF 報告或文檔的情況中,整合 IronPDF 和 PostgreSQL 資料庫可能會非常有用。 這可以從直接從 PostgreSQL 資料庫中持續的數據生成發票、報告、客戶對帳單等。

安裝 IronPDF

在您使用 IronPDF 之前,必須將其添加到您的專案中。 這可以通過 NuGet 套件管理器輕鬆完成:

Install-Package IronPdf

從 PostgreSQL 數據生成 PDF

在這個例子中,讓我們生成一個列出我們的 PostgreSQL 資料庫中的員工的簡單 PDF 報告。 我們假設您已經按照前面章節所述設置了 AppDbContextEmployee 模型。

首先,確保您的專案中已安裝 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
$vbLabelText   $csharpLabel

輸出

當您運行代碼時,這個控制台輸出會顯示:

! C# PostgreSQL (開發者如何工作):圖 4 - 控制台輸出

生成的這個 PDF 是:

! C# PostgreSQL (開發者如何工作):圖 5 - 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服務器正在運行,並檢查是否有任何防火牆或網絡問題可能阻止了連接。

Curtis Chau
技術作家

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

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