跳過到頁腳內容
.NET幫助

C# MySQL連接(開發者如何理解其工作)

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 root 用戶憑證,並確保 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 資料庫

在 C# 中安裝 MySql.Data 函式庫

要將 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 列。

使用 IronPDF 從 MySQL 資料生成 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 外觀的能力,確保其滿足您的特定要求。

在C#項目中設置IronPDF

要使用IronPDF,在Visual Studio中通過NuGet Package Manager安裝它:

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):

    • 使用MySqlCommand與參數化查詢(如@FirstName@LastName等)以防止 SQL 注入。
    • 打開連接(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

結論

在本文中,我們走過了將 MySQL 與 C# 應用程式整合的基本步驟。 從設置資料庫和進行 CRUD 操作到使用 IronPDF 生成 PDF,我們涵蓋了一系列對於構建數據驅動應用程式至關重要的基本主題。 以下是主要概念的回顧:

  • MySQL 和 C# 整合:我們演示了如何使用 MySql.Data 函式庫連接到 MySQL 資料庫,管理資料庫連接,並使用參數化查詢執行 CRUD 操作。 這確保了可以安全和有組織地高效儲存、更新和檢索數據。
  • 執行 CRUD 操作:通過插入、更新和讀取員工數據的範例方法,您可以擴展此邏輯來管理真實世界資料庫中的其他類型的記錄。 使用參數化查詢同時有助於減少 SQL 注入攻擊,確保您的應用程式安全。
  • IronPDF 用於 PDF 生成:IronPDF 可以從動態 HTML 內容中輕鬆生成專業外觀的 PDF。 通過將從 MySQL 中提取的數據轉換為 HTML 表格,我們可以創建自定義報告並將其保存為 PDF,這對於生成發票、報表、摘要等都非常有用。 IronPDF 簡單明了的 API 使其成為任何需要在應用程式中處理 PDF 生成的 C# 開發人員的絕佳工具。

通過將 C# 和 MySQL 組合在一起,開發人員可以構建能夠儲存和管理數據的強大應用程式,同時提供 PDF 報告等高級功能。 這些功能在金融到醫療保健等各行業中都非常有用,因為精確的數據管理和報告是至關重要的。

對於希望將 PDF 生成納入 C# 應用程式的開發人員,IronPDF允許您測試完整的功能套件。 無論您是需要生成簡單的文檔還是複雜的報告,IronPDF 都可以成為在您的工作流程中自動化 PDF 創建的無價之寶。

常見問題解答

將 MySQL 與 C# 應用程式整合的先決條件是什麼?

要將 MySQL 整合到 C# 應用程式中,您需要像 Visual Studio 這樣的 IDE、正在運行的 MySQL 數據庫以及從數據庫內容中生成 PDF 的 IronPDF。

如何使用 C# 將 MySQL 數據轉換為 PDF?

您可以先將 MySQL 數據轉換為 HTML 字符串,然後使用 IronPDF 的 RenderHtmlAsPdf 方法生成 PDF 文檔。

如何安裝和配置 MySQL 以作為 C# 使用?

通過從 mysql.com 下載 MySQL 安裝程式,運行安裝程式並按照設置指示進行安裝。選擇 'Developer Default' 設置包括 MySQL Server 和 Workbench,並配置 root 用戶憑證。

推薦用於 C# 和 MySQL 數據庫連接的庫是什麼?

推薦使用 MySQL Connector/NET 庫來建立 C# 應用程式與 MySQL 數據庫之間的連接。它允許使用連接字串來促進通信。

如何在使用 C# 與 MySQL 時保護我的 SQL 查詢?

為了保護 SQL 查詢,請使用參數化查詢,這有助於防止通過確保正確的輸入驗證來進行 SQL 注入攻擊。

在 MySQL 和 C# 的上下文中,連接池是什麼?

連接池是指重用來自池的數據庫連接的做法,通過減少反复打開和關閉連接的開銷來提高效率。

如何在 MySQL 中創建 C# 整合的樣本數據庫和表格?

打開 MySQL Workbench,連接到您的伺服器,並使用如 CREATE DATABASE SampleDB;CREATE TABLE Employees (...); 的 SQL 命令設置樣本數據庫和表格。

我應該在 C# 應用程式的 PDF 庫中尋找哪些特性?

一個強大的 C# PDF 庫應提供像 HTML to PDF 轉換、PDF 編輯、合併和拆分,以及使用 CSS 應用自定義樣式的功能,例如 IronPDF 提供的那些功能。

如何使用 C# 對 MySQL 數據庫執行 CRUD 操作?

通過在 C# 中創建一個輔助類,使用方法中的參數化 SQL 命令來插入、讀取、更新和刪除 MySQL 數據庫中的數據以實現 CRUD 操作。

如何使用 C# 更新 MySQL 數據庫中的員工詳細信息?

通過在 C# 中編寫一個方法來更新員工詳細信息,該方法使用參數化的 UPDATE SQL 命令,允許根據 EmployeeID 進行諸如薪資更新之類的修改。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。