.NET ヘルプ

C# PostgreSQL(開発者にとっての仕組み)

更新済み 4月 3, 2024
共有:

このチュートリアルへようこそ。C#アプリケーションを統合することに興味がある初学者のために設計されています。 ポストグレスキューエル. PostgreSQLは、最も使用されているリレーショナルデータベースの1つであり、信頼性が高く、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(ドットネット コア)) プロジェクトの種類として「simple」に設定することで、物事を簡単に保つことができます。

C#とPostgreSQLの統合

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#

localhostyourpassword、および mydatabase は、PostgreSQLサーバーの詳細に置き換えてください。

従業員モデルの定義

私たちは、PostgreSQLデータベースでデータを表すEmployeeエンティティモデルを定義します。 このモデルには、データベーステーブルの列に対応するプロパティが含まれています。

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#

このコードスニペットは、2つのプロパティ IdLastName を持つシンプルな Employee クラスを定義しています。 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 従業員 { 取得; セット; } はPostgreSQLデータベース内のemployeeテーブルにマッピングされた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テーブルが空であるかどうかを確認し、空であれば、プログラムが新しいEmployeeを「Software」という姓で追加し、変更をデータベースに保存します。 プログラムは Employees テーブルを検索し、「Software」という姓を持つレコードの詳細をコンソールに出力します。 Postgresデータベースにテーブルを削除するためのSQLクエリを追加できます。 私たちは、データベース用の.NETデータプロバイダーを追加することもできます。

出力

プログラムを実行したときのコンソール出力は次のとおりです:

C# PostgreSQL(開発者向けの動作方法):図2 ー 出力

そして、PgAdminのテーブルデータです:

C# PostgreSQL(開発者向けの仕組み):図3 - テーブル出力

IronPDFの紹介

IronPDF は、C#用の包括的なライブラリであり、開発者が.NETアプリケーション内でPDFドキュメントを作成、編集、および操作することを可能にします。 以下の内容を日本語に翻訳してください:

この強力なツールは、 HTMLからPDFを生成する、URL、画像。 また、テキストや画像の編集、暗号化やデジタル署名などのセキュリティ機能の追加といった基本的なPDF操作も提供します。 IronPDFは、その使いやすさで際立っており、開発者が最小限のコードで複雑なPDF機能を実装できるようにします。

PostgreSQLデータベースとIronPDFを統合することは、データベースに保存された動的データに基づいてPDFレポートやドキュメントを生成する必要のあるシナリオで非常に有用です。 これは、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
VB   C#

出力

コードを実行すると、このコンソール出力が表示されます:

C# PostgreSQL(開発者向けの仕組み):図4 - コンソール出力

このPDFは生成されたものです:

C# PostgreSQL(開発者向けの仕組み):図5 - PDF出力

結論

データベース管理の世界に、C#とPostgreSQLを使って重要な第一歩を踏み出しました。 このチュートリアルの指示に従うことで、Visual Studioでプロジェクトを設定し、必要なパッケージをインストールし、基本的なデータベース操作を実行する方法を学びました。 これらの概念に慣れてくると、C#と最も重要なリレーショナルデータベースシステムの一つを組み合わせることで得られるパワーと柔軟性を発見するでしょう。 さまざまなクエリやエンティティ構成を試してみて、C#がPostgreSQLとどのように相互作用するかについての理解を深めてください。

IronPDFは、 無料試用 初期投資なしでその機能と性能を開発者が探索できるようにします。 このトライアルは、.NET アプリケーションで PDF ドキュメントの生成、編集、変換に対する IronPDF がプロジェクトの要件をどれだけ満たすかを評価するのに特に役立ちます。 試用期間後、または本番環境で使用する場合は、ライセンスの取得が必要です。 IronPDFのライセンスは$749から始まり、さまざまな開発ニーズに対応する機能とサポートオプションを提供します。

< 以前
ネイティブUI C#(開発者向けの動作方法)
次へ >
C# パラメータ (開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >