.NET 帮助

C# PostgreSQL(对开发人员的工作原理)

发布 2024年四月3日
分享:

欢迎阅读本教程,本教程专为有兴趣将 C# 应用程序与 PostgreSQL.PostgreSQL 是全球使用最多的关系型数据库之一,以其可靠性和与包括 C# 在内的大量编程环境的兼容性而著称。本指南将指导你学习将 C# 应用程序连接到 PostgreSQL 数据库、执行 SQL 语句查询和处理数据的基础知识。我们将使用 Visual Studio、NuGet Package Manager 和 Npgsql 数据提供程序等工具,创建一个与 PostgreSQL 服务器通信的简单项目。我们还将学习与 PostgreSQL 集成的 IronPDF 库。

设置你的环境

在开始编码之前,请确保计算机上安装了 Visual Studio。Visual Studio 是一种流行的集成开发环境 (IDE) 它支持 C# 和其他编程语言。在数据库管理方面,可在本地计算机上安装 PostgreSQL,或在 Azure Database 等云环境中建立 PostgreSQL 数据库。

设置好 Visual Studio 和 PostgreSQL 服务器后,创建一个新的 C# 项目。方法是打开 Visual Studio,进入 "文件 "菜单,选择 "新建",然后选择 "项目"。选择控制台应用程序 (.NET Core) 作为项目类型,以保持简单。

将 PostgreSQL 与 C&num 整合;

要将 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 属性公共 DbSet员工 { 获取;设置; }声明一组雇员实体,这些实体映射到 PostgreSQL 数据库中的雇员表。

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 数据提供程序。

输出

下面是运行程序时的控制台输出:

C# PostgreSQL(如何为开发人员工作):图 2 - 输出

这就是 PgAdmin 中的表格数据:

C# PostgreSQL(如何为开发人员工作):图 3 - 表输出

IronPDF 简介

IronPDF 是一个全面的 C# 库,使开发人员能够在 .NET 应用程序中创建、编辑和处理 PDF 文档。这个强大的工具简化了 从 HTML 生成 PDFURL 和图像。它还提供基本的 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.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >