在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
欢迎来到为希望将 C# 应用程序集成到 PostgreSQL 的初学者准备的本教程。 PostgreSQL 是全球使用最广泛的关系数据库之一,以其可靠性和与包括 C# 在内的各种编程环境的兼容性而闻名。 本指南将带您了解将 C# 应用程序连接到 PostgreSQL 数据库、执行 SQL 语句查询和处理数据的基础知识。 我们将使用工具如Visual Studio、NuGet包管理器和Npgsql数据提供者来创建一个与PostgreSQL服务器通信的简单项目。 我们还将学习集成PostgreSQL的IronPDF库。
在开始编码之前,请确保您的电脑上已安装 Visual Studio。 Visual Studio 是一个流行的集成开发环境 (IDE),支持 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”的条目,并将其详细信息打印到控制台。 我们可以添加一个SQL查询来删除Postgres数据库中的表。 我们还可以为我们的数据库添加一个 .NET 数据提供程序。
这是运行程序时的控制台输出:
这是PgAdmin中的表数据:
探索 IronPDF 库功能以了解这个全面的 C# 库如何使开发人员能够在 .NET 应用程序中创建、编辑和操作 PDF 文档。 这款强大的工具简化了从HTML、网址和图像生成PDF的过程。 它还提供了基本的PDF操作,例如编辑文字和图像,以及添加加密和数字签名等安全功能。 IronPDF以其易用性脱颖而出,开发人员只需少量代码即可实现复杂的PDF功能。
IronPDF 提供将 HTML 无缝转换为 PDF 的功能,同时保持布局和样式不变。 此功能非常适合从基于网络的内容生成PDF文件,例如报告、发票和文档。 它将 HTML 文件、URLs 和 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
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,提供适合不同开发需求的一系列功能和支持选项。