フッターコンテンツにスキップ
.NETヘルプ

C# MySQL Connection(開発者向けの仕組み)

C# MySQL 統合の紹介

C# アプリケーションを MySQL データベースに接続することで、開発者は関係データベースの強力さを活用してデータの保存、取得、管理を効率的に行うことができます。 This guide provides a step-by-step process to integrate MySQL with C# applications and demonstrates how to generate PDFs from the data within your MySQL database using the IronPDF library.

前提条件

このガイドに従うには、以下が必要です。

  • Visual Studio または任意の C# IDE
  • MySQL データベース(インストール済みかつ稼働中)
  • IronPDF ライブラリ(PDF 生成用)

MySQL データベースの設定

MySQL のインストールと設定

  1. mysql.com から MySQL の最新バージョンをダウンロードします。
  2. インストーラーを実行し、セットアップ手順に従います。 「開発者デフォルト」を選択して MySQL サーバーと MySQL Workbench を含めます。
  3. セットアップ中に MySQL ルートユーザーの資格情報を設定し、MySQL サービスが稼働していることを確認します。

サンプルデータベースとテーブルの作成

  1. MySQL Workbench を開き、サーバーに接続します。
  2. 新しいデータベースおよびサンプルテーブルを SQL コマンドを使用して作成します。
CREATE DATABASE SampleDB;
USE SampleDB;
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY AUTO_INCREMENT,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    Position VARCHAR(50),
    Salary DECIMAL(10, 2)
);
  1. サンプルデータを挿入します。
INSERT INTO Employees (FirstName, LastName, Position, Salary) 
VALUES ('John', 'Doe', 'Software Developer', 80000),
       ('Jane', 'Smith', 'Data Analyst', 75000);

MySQL ユーザーのリモートアクセス設定 (オプション)

リモートアクセス用に、必要な権限を持つ MySQL ユーザーを作成します。

CREATE USER 'remoteUser'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON SampleDB.* TO 'remoteUser'@'%';
FLUSH PRIVILEGES;

C# を MySQL データベースに接続する

MySql.Data ライブラリの C# へのインストール

C# アプリケーションを MySQL に接続するには、MySQL Connector/NET ライブラリ(Connector/NET と呼ばれることが多い)を使用します。 これは MySQL の公式 .NET ドライバーで、NuGet 経由でインストールできます。

  1. Visual Studioを開き、新しいC#コンソールアプリケーションを作成します。
  2. NuGet パッケージ マネージャーを使用して MySql.Data ライブラリを追加します:
    • プロジェクトを右クリック > NuGet パッケージの管理 > 参照 > MySql.Data を探してインストールします。

接続コードを書く

以下のコード例は、MySQL に接続を確立する方法を示しています。

using System;
using MySql.Data.MySqlClient;

public class Program
{
    // Connection string containing the server, database, user credentials, etc.
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    private void Initialize()
    {
        // Create a MySQL connection object
        MySqlConnection connection = new MySqlConnection(connectionString);
        try
        {
            connection.Open();
            Console.WriteLine("Connected to MySQL Database!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            connection.Close(); // Ensure the connection is closed after use
        }
    }
}
using System;
using MySql.Data.MySqlClient;

public class Program
{
    // Connection string containing the server, database, user credentials, etc.
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    private void Initialize()
    {
        // Create a MySQL connection object
        MySqlConnection connection = new MySqlConnection(connectionString);
        try
        {
            connection.Open();
            Console.WriteLine("Connected to MySQL Database!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            connection.Close(); // Ensure the connection is closed after use
        }
    }
}
Imports System
Imports MySql.Data.MySqlClient

Public Class Program
	' Connection string containing the server, database, user credentials, etc.
	Private connectionString As String = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;"

	Private Sub Initialize()
		' Create a MySQL connection object
		Dim connection As New MySqlConnection(connectionString)
		Try
			connection.Open()
			Console.WriteLine("Connected to MySQL Database!")
		Catch ex As Exception
			Console.WriteLine($"Error: {ex.Message}")
		Finally
			connection.Close() ' Ensure the connection is closed after use
		End Try
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • 接続文字列: サーバー、データベース名、ユーザー ID、およびパスワードなどの詳細を含みます。
  • MySqlConnection: 接続を確立するために使用されます。
  • Open() メソッド: 接続を開こうとします。
  • 例外処理: コネクションエラーを優雅に処理するために例外をキャッチします。

DNS SRV レコードを使用した接続 (オプション)

アプリケーションがクラウドにホストされているか、DNS SRV レコードを介して MySQL データベースに接続する必要がある場合は、サーバー名の代わりにデータベースの IP に解決される対応する DNS エントリを使用できます。

string connectionString = "Server=mysql.example.com;Database=SampleDB;User ID=root;Password=yourpassword;";
string connectionString = "Server=mysql.example.com;Database=SampleDB;User ID=root;Password=yourpassword;";
Dim connectionString As String = "Server=mysql.example.com;Database=SampleDB;User ID=root;Password=yourpassword;"
$vbLabelText   $csharpLabel

コネクションプール

デフォルトで、MySQL Connector/NET はコネクションプールをサポートしており、データベース接続をより効率的に管理するのに役立ちます。 コネクションプールは、プールから既存の接続を再利用することで、接続を開閉するオーバーヘッドを削減します。

コネクションプールの動作をカスタマイズしたい場合は、接続文字列を次のように調整できます。

string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;Pooling=true;";
string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;Pooling=true;";
Dim connectionString As String = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;Pooling=true;"
$vbLabelText   $csharpLabel

一般的なエラーの処理

一般的な問題には、誤った接続文字列、ファイアウォールの制限、または MySQL サービスが稼働していないことが含まれます。 すべての構成詳細が正しいこと、および MySQL サービスがアクティブであることを確認してください。

C# と MySQL での CRUD 操作の実行

データベース操作用の C# クラスの作成

コードの組織化のために、すべてのデータベース操作を処理する DatabaseHelper クラスを作成します。 このクラスは、データの挿入、読み取り、更新、および削除 (CRUD) 操作のメソッドを含みます。

using System;
using MySql.Data.MySqlClient;

public class DatabaseHelper
{
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    // Method to insert a new employee record
    public void InsertEmployee(string firstName, string lastName, string position, decimal salary)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Position, Salary) VALUES (@FirstName, @LastName, @Position, @Salary)";
            MySqlCommand cmd = new MySqlCommand(query, connection);

            // Add parameters to prevent SQL injection
            cmd.Parameters.AddWithValue("@FirstName", firstName);
            cmd.Parameters.AddWithValue("@LastName", lastName);
            cmd.Parameters.AddWithValue("@Position", position);
            cmd.Parameters.AddWithValue("@Salary", salary);

            connection.Open();
            cmd.ExecuteNonQuery(); // Execute the insert command
        }
    }
}
using System;
using MySql.Data.MySqlClient;

public class DatabaseHelper
{
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    // Method to insert a new employee record
    public void InsertEmployee(string firstName, string lastName, string position, decimal salary)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Position, Salary) VALUES (@FirstName, @LastName, @Position, @Salary)";
            MySqlCommand cmd = new MySqlCommand(query, connection);

            // Add parameters to prevent SQL injection
            cmd.Parameters.AddWithValue("@FirstName", firstName);
            cmd.Parameters.AddWithValue("@LastName", lastName);
            cmd.Parameters.AddWithValue("@Position", position);
            cmd.Parameters.AddWithValue("@Salary", salary);

            connection.Open();
            cmd.ExecuteNonQuery(); // Execute the insert command
        }
    }
}
Imports System
Imports MySql.Data.MySqlClient

Public Class DatabaseHelper
	Private connectionString As String = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;"

	' Method to insert a new employee record
	Public Sub InsertEmployee(ByVal firstName As String, ByVal lastName As String, ByVal position As String, ByVal salary As Decimal)
		Using connection = New MySqlConnection(connectionString)
			Dim query As String = "INSERT INTO Employees (FirstName, LastName, Position, Salary) VALUES (@FirstName, @LastName, @Position, @Salary)"
			Dim cmd As New MySqlCommand(query, connection)

			' Add parameters to prevent SQL injection
			cmd.Parameters.AddWithValue("@FirstName", firstName)
			cmd.Parameters.AddWithValue("@LastName", lastName)
			cmd.Parameters.AddWithValue("@Position", position)
			cmd.Parameters.AddWithValue("@Salary", salary)

			connection.Open()
			cmd.ExecuteNonQuery() ' Execute the insert command
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • パラメータ化: @Parameter を使用すると、SQL インジェクションのリスクが軽減されます。
  • connection.Open(): MySQL 接続を開きます。
  • cmd.ExecuteNonQuery(): 挿入クエリを実行します。

MySQL データベースへのデータの挿入

新しい従業員データを追加するには、InsertEmployee メソッドを呼び出します。

DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
Dim dbHelper As New DatabaseHelper()
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000)
$vbLabelText   $csharpLabel

データの取得と表示

データを取得し、コンソールに表示します。

public void GetEmployees()
{
    using (var connection = new MySqlConnection(connectionString))
    {
        string query = "SELECT * FROM Employees";
        MySqlCommand cmd = new MySqlCommand(query, connection);
        connection.Open();

        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine($"{reader["FirstName"]} {reader["LastName"]}, Position: {reader["Position"]}, Salary: {reader["Salary"]}");
            }
        }
    }
}
public void GetEmployees()
{
    using (var connection = new MySqlConnection(connectionString))
    {
        string query = "SELECT * FROM Employees";
        MySqlCommand cmd = new MySqlCommand(query, connection);
        connection.Open();

        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine($"{reader["FirstName"]} {reader["LastName"]}, Position: {reader["Position"]}, Salary: {reader["Salary"]}");
            }
        }
    }
}
Public Sub GetEmployees()
	Using connection = New MySqlConnection(connectionString)
		Dim query As String = "SELECT * FROM Employees"
		Dim cmd As New MySqlCommand(query, connection)
		connection.Open()

		Using reader As MySqlDataReader = cmd.ExecuteReader()
			Do While reader.Read()
				Console.WriteLine($"{reader("FirstName")} {reader("LastName")}, Position: {reader("Position")}, Salary: {reader("Salary")}")
			Loop
		End Using
	End Using
End Sub
$vbLabelText   $csharpLabel

説明:

  • ExecuteReader(): セレクトクエリを実行し、MySqlDataReader オブジェクトを返します。
  • reader.Read(): 結果セットを反復処理し、各従業員の詳細を表示します。

レコードの更新と削除

従業員の給料を更新する例は次のとおりです。

public void UpdateEmployeeSalary(int employeeId, decimal newSalary)
{
    using (var connection = new MySqlConnection(connectionString))
    {
        string query = "UPDATE Employees SET Salary = @Salary WHERE EmployeeID = @EmployeeID";
        MySqlCommand cmd = new MySqlCommand(query, connection);

        // Parameterize the SQL command
        cmd.Parameters.AddWithValue("@Salary", newSalary);
        cmd.Parameters.AddWithValue("@EmployeeID", employeeId);

        connection.Open();
        cmd.ExecuteNonQuery(); // Execute the update command
        Console.WriteLine("Employee salary updated successfully!");
    }
}
public void UpdateEmployeeSalary(int employeeId, decimal newSalary)
{
    using (var connection = new MySqlConnection(connectionString))
    {
        string query = "UPDATE Employees SET Salary = @Salary WHERE EmployeeID = @EmployeeID";
        MySqlCommand cmd = new MySqlCommand(query, connection);

        // Parameterize the SQL command
        cmd.Parameters.AddWithValue("@Salary", newSalary);
        cmd.Parameters.AddWithValue("@EmployeeID", employeeId);

        connection.Open();
        cmd.ExecuteNonQuery(); // Execute the update command
        Console.WriteLine("Employee salary updated successfully!");
    }
}
Public Sub UpdateEmployeeSalary(ByVal employeeId As Integer, ByVal newSalary As Decimal)
	Using connection = New MySqlConnection(connectionString)
		Dim query As String = "UPDATE Employees SET Salary = @Salary WHERE EmployeeID = @EmployeeID"
		Dim cmd As New MySqlCommand(query, connection)

		' Parameterize the SQL command
		cmd.Parameters.AddWithValue("@Salary", newSalary)
		cmd.Parameters.AddWithValue("@EmployeeID", employeeId)

		connection.Open()
		cmd.ExecuteNonQuery() ' Execute the update command
		Console.WriteLine("Employee salary updated successfully!")
	End Using
End Sub
$vbLabelText   $csharpLabel

更新コマンド: EmployeeID に基づいて Salary 列を更新するためにパラメータ化されたクエリを使用します。

MySQL データを IronPDF を使って PDF 生成

IronPDFの紹介

IronPDF は、開発者が C# アプリケーション内で簡単に PDF ドキュメントを作成、編集、操作できる強力なライブラリです。 さまざまな PDF 機能をサポートしており、自動レポート生成、ドキュメント操作、HTML から PDF への変換が必要となるデータ駆動型アプリケーションにとって理想的なツールです。 動的ウェブページを PDF ファイルに変換する必要がある場合でも、ゼロからカスタム PDF を生成する必要がある場合でも、IronPDF は数行のコードでそのプロセスを簡素化します。

IronPDFの主な機能

  • HTML から PDF への変換: IronPDF の目玉機能の一つは、HTML コンテンツを完全にフォーマットされた PDF ドキュメントに変換できることです。 この機能は、動的なウェブコンテンツからレポートを生成する場合やウェブ形式で保存されたデータを処理する場合に特に便利です。
  • PDF の編集: IronPDF では、既存の PDF を編集して、テキスト、画像、テーブルなどのコンテンツを追加、削除、変更できます。 これは、既存のドキュメントを処理または更新する必要のあるアプリケーションに最適です。
  • PDF Merging and Splitting: With IronPDF, you can easily merge multiple PDFs into a single document or split a large PDF into smaller files. この機能は、大量のドキュメントを整理および管理するのに役立ちます。
  • スタイリングとカスタマイズ: HTML から PDF を生成する際に、CSS を使用してドキュメントをスタイルし、アプリケーションのデザインに合ったカスタムレイアウトを実現できます。 IronPDF は PDF の外観を完全に制御することができ、特定の要件に見合った内容にすることを保証します。

IronPDF を C# プロジェクトに設定する

IronPDF を使用するには、NuGet パッケージマネージャーを使用して Visual Studio にインストールします。

Install-Package IronPdf

MySQL データを PDF 形式に変換

ここに従業員データの PDF レポートを作成する方法を示した完全なコード例があります。

using System;
using MySql.Data.MySqlClient;
using IronPdf;

public class Program
{
    private static string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    public static void Main(string[] args)
    {
        // Perform CRUD operations
        DatabaseHelper dbHelper = new DatabaseHelper();
        // Insert a new employee
        dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
        // Display employees
        dbHelper.GetEmployees();
        // Update an employee's salary
        dbHelper.UpdateEmployeeSalary(1, 95000);
        // Generate a PDF report
        dbHelper.GenerateEmployeeReportPDF();
        Console.WriteLine("Operations completed.");
    }
}

public class DatabaseHelper
{
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    // Insert employee into database
    public void InsertEmployee(string firstName, string lastName, string position, decimal salary)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Position, Salary) VALUES (@FirstName, @LastName, @Position, @Salary)";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@FirstName", firstName);
            cmd.Parameters.AddWithValue("@LastName", lastName);
            cmd.Parameters.AddWithValue("@Position", position);
            cmd.Parameters.AddWithValue("@Salary", salary);
            connection.Open();
            cmd.ExecuteNonQuery();
            Console.WriteLine($"Employee {firstName} {lastName} inserted successfully!");
        }
    }

    // Get employees from the database and display them
    public void GetEmployees()
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "SELECT * FROM Employees";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            connection.Open();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                Console.WriteLine("\nEmployee List:");
                while (reader.Read())
                {
                    Console.WriteLine($"{reader["EmployeeID"]} - {reader["FirstName"]} {reader["LastName"]}, Position: {reader["Position"]}, Salary: {reader["Salary"]}");
                }
            }
        }
    }

    // Update the salary of an employee
    public void UpdateEmployeeSalary(int employeeId, decimal newSalary)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "UPDATE Employees SET Salary = @Salary WHERE EmployeeID = @EmployeeID";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@Salary", newSalary);
            cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
            connection.Open();
            cmd.ExecuteNonQuery();
            Console.WriteLine($"Employee ID {employeeId}'s salary updated to {newSalary}.");
        }
    }

    // Generate a PDF report of all employees
    public void GenerateEmployeeReportPDF()
    {
        string htmlContent = "<h1>Employee Report</h1><table border='1'><tr><th>EmployeeID</th><th>First Name</th><th>Last Name</th><th>Position</th><th>Salary</th></tr>";

        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "SELECT * FROM Employees";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            connection.Open();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    htmlContent += $"<tr><td>{reader["EmployeeID"]}</td><td>{reader["FirstName"]}</td><td>{reader["LastName"]}</td><td>{reader["Position"]}</td><td>{reader["Salary"]}</td></tr>";
                }
            }
        }

        htmlContent += "</table>";

        // Use IronPDF to convert HTML to PDF
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("EmployeeReport.pdf");
        Console.WriteLine("PDF Report generated successfully!");
    }
}
using System;
using MySql.Data.MySqlClient;
using IronPdf;

public class Program
{
    private static string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    public static void Main(string[] args)
    {
        // Perform CRUD operations
        DatabaseHelper dbHelper = new DatabaseHelper();
        // Insert a new employee
        dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
        // Display employees
        dbHelper.GetEmployees();
        // Update an employee's salary
        dbHelper.UpdateEmployeeSalary(1, 95000);
        // Generate a PDF report
        dbHelper.GenerateEmployeeReportPDF();
        Console.WriteLine("Operations completed.");
    }
}

public class DatabaseHelper
{
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";

    // Insert employee into database
    public void InsertEmployee(string firstName, string lastName, string position, decimal salary)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "INSERT INTO Employees (FirstName, LastName, Position, Salary) VALUES (@FirstName, @LastName, @Position, @Salary)";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@FirstName", firstName);
            cmd.Parameters.AddWithValue("@LastName", lastName);
            cmd.Parameters.AddWithValue("@Position", position);
            cmd.Parameters.AddWithValue("@Salary", salary);
            connection.Open();
            cmd.ExecuteNonQuery();
            Console.WriteLine($"Employee {firstName} {lastName} inserted successfully!");
        }
    }

    // Get employees from the database and display them
    public void GetEmployees()
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "SELECT * FROM Employees";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            connection.Open();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                Console.WriteLine("\nEmployee List:");
                while (reader.Read())
                {
                    Console.WriteLine($"{reader["EmployeeID"]} - {reader["FirstName"]} {reader["LastName"]}, Position: {reader["Position"]}, Salary: {reader["Salary"]}");
                }
            }
        }
    }

    // Update the salary of an employee
    public void UpdateEmployeeSalary(int employeeId, decimal newSalary)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "UPDATE Employees SET Salary = @Salary WHERE EmployeeID = @EmployeeID";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@Salary", newSalary);
            cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
            connection.Open();
            cmd.ExecuteNonQuery();
            Console.WriteLine($"Employee ID {employeeId}'s salary updated to {newSalary}.");
        }
    }

    // Generate a PDF report of all employees
    public void GenerateEmployeeReportPDF()
    {
        string htmlContent = "<h1>Employee Report</h1><table border='1'><tr><th>EmployeeID</th><th>First Name</th><th>Last Name</th><th>Position</th><th>Salary</th></tr>";

        using (var connection = new MySqlConnection(connectionString))
        {
            string query = "SELECT * FROM Employees";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            connection.Open();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    htmlContent += $"<tr><td>{reader["EmployeeID"]}</td><td>{reader["FirstName"]}</td><td>{reader["LastName"]}</td><td>{reader["Position"]}</td><td>{reader["Salary"]}</td></tr>";
                }
            }
        }

        htmlContent += "</table>";

        // Use IronPDF to convert HTML to PDF
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("EmployeeReport.pdf");
        Console.WriteLine("PDF Report generated successfully!");
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports MySql.Data.MySqlClient
Imports IronPdf

Public Class Program
	Private Shared connectionString As String = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;"

	Public Shared Sub Main(ByVal args() As String)
		' Perform CRUD operations
		Dim dbHelper As New DatabaseHelper()
		' Insert a new employee
		dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000)
		' Display employees
		dbHelper.GetEmployees()
		' Update an employee's salary
		dbHelper.UpdateEmployeeSalary(1, 95000)
		' Generate a PDF report
		dbHelper.GenerateEmployeeReportPDF()
		Console.WriteLine("Operations completed.")
	End Sub
End Class

Public Class DatabaseHelper
	Private connectionString As String = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;"

	' Insert employee into database
	Public Sub InsertEmployee(ByVal firstName As String, ByVal lastName As String, ByVal position As String, ByVal salary As Decimal)
		Using connection = New MySqlConnection(connectionString)
			Dim query As String = "INSERT INTO Employees (FirstName, LastName, Position, Salary) VALUES (@FirstName, @LastName, @Position, @Salary)"
			Dim cmd As New MySqlCommand(query, connection)
			cmd.Parameters.AddWithValue("@FirstName", firstName)
			cmd.Parameters.AddWithValue("@LastName", lastName)
			cmd.Parameters.AddWithValue("@Position", position)
			cmd.Parameters.AddWithValue("@Salary", salary)
			connection.Open()
			cmd.ExecuteNonQuery()
			Console.WriteLine($"Employee {firstName} {lastName} inserted successfully!")
		End Using
	End Sub

	' Get employees from the database and display them
	Public Sub GetEmployees()
		Using connection = New MySqlConnection(connectionString)
			Dim query As String = "SELECT * FROM Employees"
			Dim cmd As New MySqlCommand(query, connection)
			connection.Open()

			Using reader As MySqlDataReader = cmd.ExecuteReader()
				Console.WriteLine(vbLf & "Employee List:")
				Do While reader.Read()
					Console.WriteLine($"{reader("EmployeeID")} - {reader("FirstName")} {reader("LastName")}, Position: {reader("Position")}, Salary: {reader("Salary")}")
				Loop
			End Using
		End Using
	End Sub

	' Update the salary of an employee
	Public Sub UpdateEmployeeSalary(ByVal employeeId As Integer, ByVal newSalary As Decimal)
		Using connection = New MySqlConnection(connectionString)
			Dim query As String = "UPDATE Employees SET Salary = @Salary WHERE EmployeeID = @EmployeeID"
			Dim cmd As New MySqlCommand(query, connection)
			cmd.Parameters.AddWithValue("@Salary", newSalary)
			cmd.Parameters.AddWithValue("@EmployeeID", employeeId)
			connection.Open()
			cmd.ExecuteNonQuery()
			Console.WriteLine($"Employee ID {employeeId}'s salary updated to {newSalary}.")
		End Using
	End Sub

	' Generate a PDF report of all employees
	Public Sub GenerateEmployeeReportPDF()
		Dim htmlContent As String = "<h1>Employee Report</h1><table border='1'><tr><th>EmployeeID</th><th>First Name</th><th>Last Name</th><th>Position</th><th>Salary</th></tr>"

		Using connection = New MySqlConnection(connectionString)
			Dim query As String = "SELECT * FROM Employees"
			Dim cmd As New MySqlCommand(query, connection)
			connection.Open()

			Using reader As MySqlDataReader = cmd.ExecuteReader()
				Do While reader.Read()
					htmlContent &= $"<tr><td>{reader("EmployeeID")}</td><td>{reader("FirstName")}</td><td>{reader("LastName")}</td><td>{reader("Position")}</td><td>{reader("Salary")}</td></tr>"
				Loop
			End Using
		End Using

		htmlContent &= "</table>"

		' Use IronPDF to convert HTML to PDF
		Dim renderer As New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		pdf.SaveAs("EmployeeReport.pdf")
		Console.WriteLine("PDF Report generated successfully!")
	End Sub
End Class
$vbLabelText   $csharpLabel

コードの内訳

  1. MySQL データベースへの接続:

    • connectionString では、MySQL サーバー、データベース、ユーザー、およびパスワードを定義します。
    • MySqlConnection を使用して接続し、MySqlCommand で CRUD 操作を行います。
  2. 挿入操作 (InsertEmployee):

    • SQL インジェクションを防ぐために、パラメータ化されたクエリ (@FirstName, @LastName など) を使用した MySqlCommand を使用します。
    • 接続を開いた後 (connection.Open()) に、ExecuteNonQuery() で INSERT SQL ステートメントを実行します。
  3. 読み取り操作 (GetEmployees):

    • 従業員のすべてのレコードを取得するために SELECT * クエリを実行します。
    • MySqlDataReader を使用して結果セットを反復処理し、コンソールに各レコードを表示します。
  4. 更新操作 (UpdateEmployeeSalary):

    • メソッドは employeeId および newSalary を受け取って従業員の給料を更新します。
    • パラメータ化された UPDATE SQL クエリを使用します。
  5. PDF 生成 (GenerateEmployeeReportPDF):
    • シンプルなテーブル構造で従業員データを HTML 文字列に収集します。
    • HTML コンテンツは IronPDF の RenderHtmlAsPdf メソッドに渡され、PDF レポートが生成されます。
    • 結果として得られた PDF は EmployeeReport.pdf として保存されます。

結論

この記事では、C# アプリケーションに MySQL を統合するための基本ステップを紹介しました。 データベースの設定、CRUD 操作の実行から IronPDF を使用した PDF の生成まで、データ駆動型アプリケーションを構築するために重要な基本的なトピックを幅広く取り上げました。 以下に主要概念の概要を示します。

  • MySQL と C# の統合: MySql.Data ライブラリを使用して MySQL データベースに接続する方法、データベース接続の管理、パラメータ化クエリを使用して CRUD 操作を実行する方法を紹介しました。 これにより、データが安全かつ効率的に保存、更新、取得できるようになります。
  • CRUD 操作の実行: 従業員データを挿入、更新、読み取りするための例のメソッドによって、このロジックを拡張して現実世界のデータベースの他のタイプのレコードを管理することができます。 パラメータ化クエリを使用することで、SQL インジェクション攻撃を軽減し、アプリケーションのセキュリティを確保します。
  • IronPDF を使った PDF 生成: IronPDF を使用すると、動的 HTML コンテンツからプロフェッショナルな外観の PDF を簡単に生成することができます。 MySQL から取得したデータを HTML テーブルに変換することで、カスタマイズされたレポートを作成し、PDF として保存できます。これにより、請求書、レポート、サマリーなどの生成が容易になります。 IronPDF のわかりやすい API により、C# 開発者がアプリケーション内で PDF 生成を扱うための優れたツールとなります。

C# と MySQL を組み合わせることで、開発者はデータの管理と高度な機能(たとえば PDF レポートの生成)を提供しつつ、データを保存および管理する強力なアプリケーションを構築できます。 これらの機能は、金融からヘルスケアに至るまで、厳密なデータ管理とレポート作成が重要な様々な業界で役立ちます。

C# アプリケーションに PDF 生成を組み込むことを考えている開発者向けに、フル機能を試すことができる IronPDF があります。 簡単なドキュメントから高度なレポートまで生成が必要な場合、IronPDF はワークフロー内での PDF 自動生成のための貴重なツールとなります。

よくある質問

C#アプリケーションとMySQLを統合するための前提条件は何ですか?

MySQLをC#アプリケーションと統合するには、Visual StudioのようなIDE、稼働中のMySQLデータベース、およびデータベースコンテンツからPDFを生成するためのIronPDFが必要です。

C#を使用してMySQLデータをPDFに変換するにはどうすればよいですか?

MySQLデータをPDFに変換するには、まずデータをHTML文字列に変換し、次にIronPDFのRenderHtmlAsPdfメソッドを使用してPDFドキュメントを生成します。

C#で使用するためにMySQLをインストールおよび設定するにはどうすればよいですか?

mysql.comからMySQLをダウンロードしてインストーラーを実行し、セットアップ指示に従います。MySQL ServerとWorkbenchを含むようにセットアップで「Developer Default」を選択し、ルートユーザーのクレデンシャルを設定します。

C#とMySQLデータベースの接続性に推奨されるライブラリは何ですか?

C#アプリケーションとMySQLデータベース間の接続を確立するには、MySQL Connector/NETライブラリが推奨されます。接続文字列を使用して通信を容易にすることができます。

C#とMySQLを使用する際にSQLクエリをどのように保護できますか?

SQLクエリを保護するには、パラメータ化されたクエリを使用します。これにより、適切な入力検証を通じてSQLインジェクション攻撃を防ぐことができます。

MySQLとC#の文脈での接続プールは何ですか?

接続プールは、データベース接続をプールから再利用する実践を指し、接続の開閉に関連するオーバーヘッドを削減することで効率を向上させます。

C#統合用にMySQLでサンプルのデータベースとテーブルを作成するにはどうすればよいですか?

MySQL Workbenchを開き、サーバーに接続して、CREATE DATABASE SampleDB;CREATE TABLE Employees (...);のようなSQLコマンドを使用してサンプルデータベースとテーブルを設定します。

C#アプリケーション用のPDFライブラリで探すべき特徴は何ですか?

C#用の強力なPDFライブラリは、HTMLからPDFへの変換、PDFの編集、結合および分割、CSSを使用したカスタムスタイルの適用などの機能を提供する必要があります。これらの機能はIronPDFによって提供されています。

C#を使用してMySQLデータベースでCRUD操作を実行するにはどうすればよいですか?

CRUD操作を実装するには、C#でヘルパークラスを作成し、方法内でパラメータ化されたSQLコマンドを使用して、MySQLデータベースでデータを挿入、読み取り、更新、および削除します。

C#を使用してMySQLデータベースで従業員の詳細を更新するにはどうすればよいですか?

C#でメソッドを書き、UPDATE SQLコマンドをパラメータ化して、EmployeeIDに基づいて給与の更新などの変更を許可することによって従業員の詳細を更新します。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。