跳至頁尾內容
開發者更新

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(它如何對開發者起作用):圖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

用您的PostgreSQL伺服器詳細資料替換localhostyourpassword,和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 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 Property: public DbSet<Employee> Employees { get; set; } 宣告了一組Employee實體,這些實體映射到PostgreSQL資料庫中的employee表。

  • OnConfiguring方法:此方法使用必要的資料庫連接字串配置DbContext。 用您的實際PostgreSQL伺服器詳細資料替換your_passwordyour_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}");
            }
        }
    }
}
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、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
$vbLabelText   $csharpLabel

將IronPDF與PostgreSQL資料庫相結合在需要根據儲存在資料庫中的動態資料生成PDF報告或文件的場景中非常有用。 這可能涵蓋從PostgreSQL資料庫中以直接生成發票、報告、客戶報表等範圍的用途。

安裝IronPDF

在使用IronPDF之前,您必須將其新增到您的專案中。 這可以通過NuGet Package Manager輕鬆完成:

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如何滿足您專案中生成、編輯和轉換PDF文件的需求。 在試用期之後或用於生產用途時,則需要購買授權。 IronPDF的授權從$999開始,提供適合不同開發需求的特徵和支援選項。

常見問題

如何將C#應用程式連接到PostgreSQL資料庫?

要將C#應用程式連接到PostgreSQL資料庫,您需要使用透過Visual Studio中的NuGet Package Manager安裝的Npgsql資料提供者。您還需要一個適當配置的連接字串,包括伺服器名稱、埠、使用者名、密碼和資料庫名稱。

與PostgreSQL建立C#專案的步驟有哪些?

首先,在您的機器上安裝Visual Studio和PostgreSQL。然後,建立一個新的C#專案,並使用NuGet Package Manager安裝Npgsql資料提供者。配置您的連接字串,並確保您的PostgreSQL伺服器正在運行。

如何在C#應用程式中執行SQL命令?

您可以使用Npgsql資料提供者在C#應用程式中執行SQL命令。建立與PostgreSQL資料庫的連接後,您可以使用NpgsqlCommand運行像SELECT、INSERT、UPDATE和DELETE這樣的SQL查詢。

如何從PostgreSQL資料生成PDF報告(在C#中)?

IronPDF允許您從PostgreSQL資料生成C#中的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表定義資料模型?

您可以通過建立一個與PostgreSQL表結構相對應的類來在C#中定義資料模型。類中的每個屬性應與表中的一列匹配,允許Entity Framework正確地映射資料。

如何排除C#和PostgreSQL之間的連接問題?

要排除連接問題,請確保您的連接字串配置正確、驗證您的PostgreSQL伺服器正在運行,並檢查是否有任何可能阻止連接的防火牆或網路問題。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

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

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話