.NET 幫助

C# PostgreSQL(如何為開發人員運作)

發佈 2024年4月3日
分享:

歡迎來到這個針對初學者設計的教程,適合有興趣將C#應用程式整合 PostgreSQLPostgreSQL 是全球使用最廣泛的關聯數據庫之一,以其可靠性和與包括 C# 在內的多種編程環境的兼容性而聞名。本指南將引導您了解將 C# 應用程序連接到 PostgreSQL 數據庫、執行 SQL 語句查詢和處理數據的基本知識。我們將使用 Visual Studio、NuGet 套件管理器和 Npgsql 數據提供程序等工具來創建一個與 PostgreSQL 服務器通信的簡單項目。我們還將了解結合 PostgreSQL 的 IronPDF 庫。

設定您的環境

在開始編寫程式之前,請確保您已在電腦上安裝了 Visual Studio。Visual Studio 是一個受歡迎的整合開發環境。 (集成開發環境) 支援包括 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"
VB   C#

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
VB   C#

這段程式碼片段定義了一個簡單的 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
VB   C#

DbSet 屬性public DbSet員工 { 取得;設置; }聲明一組Employee**實體,這些實體被映射到PostgreSQL資料庫中的employee表。

OnConfiguring 方法:該方法使用必要的資料庫連接字串來配置 DbContext。將 your_passwordyour_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
VB   C#

上述程式碼檢查資料庫是否存在,並在不存在的情況下創建它及其架構。這是開發新資料庫的一種簡單方式。這條 SQL 語句檢查,如果 Employees 表是空的,程式會添加一個姓「Software」的新 Employee 並將更改儲存到資料庫中。程式會查詢 Employees 表中姓「Software」的條目並將其詳細資訊打印到控制台。我們可以添加一個 SQL 查詢來刪除 Postgres 資料庫中的表。我們還可以為資料庫添加一個 .NET data provider。

輸出

當你運行程式時,這是控制台輸出:

C# PostgreSQL(對開發人員的運作方式):圖2 - 輸出

而且它是 PgAdmin 中的表格數據:

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

IronPDF 介紹

IronPDF 是一個全面的C#程式庫,允許開發者在.NET應用程式中創建、編輯和操作PDF文件。這個強大的工具簡化了 從 HTML 生成 PDF,URLs 和圖像。它還提供基本的 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
VB   C#

將IronPDF與PostgreSQL資料庫整合在一起,在需要生成基於儲存在資料庫中動態資料的PDF報表或文件的情況下,可能非常有用。這可以包括從PostgreSQL資料庫中儲存的資料直接生成發票、報表、客戶報告等。

安裝 IronPDF

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

Install-Package IronPdf

從 PostgreSQL 數據生成 PDF

在這個範例中,我們將生成一個簡單的 PDF 報告,列出我們的 PostgreSQL 數據庫中的員工。我們假設您已經按照前面的章節設置了 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
VB   C#

輸出

當您運行程式碼時,此控制臺輸出將顯示:

C# PostgreSQL(開發人員運作方式):圖4 - 控制台輸出

此 PDF 已生成:

C# PostgreSQL (如何適用於開發人員):圖 5 - PDF 輸出

結論

您剛剛踏出了以 C# 和 PostgreSQL 進行資料庫管理的重要第一步。通過本教程中的指導,您學會了如何在 Visual Studio 中設置專案、安裝必要的套件以及執行基本的資料庫操作。隨著您對這些概念的熟悉,您將發現 C# 與其中一個最重要的關聯資料庫系統結合的強大和靈活性。持續嘗試不同的查詢和實體配置,以加深您對 C# 與 PostgreSQL 互動的理解。

IronPDF 提供了 免費試用 讓開發人員在沒有任何初期投資的情況下探索其功能和能力。這個試用版對於評估 IronPDF 在 .NET 應用程式中生成、編輯和轉換 PDF 文件的需求特別有用。在試用期結束後或用於生產用途時,需要獲取許可證。IronPDF 的授權從 $749 開始,提供適合不同開發需求的各種功能和支援選項。

< 上一頁
NativeUI C#(對開發者的運作方式)
下一個 >
C# 參數(它是如何為開發人員工作的)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >