跳至頁尾內容
開發者更新

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

C# MySQL 整合介紹

將 C# 應用程式連接到 MySQL 資料庫使開發者能夠有效地利用關聯資料庫的強大功能來儲存、檢索和管理資料。 本指南提供了將 MySQL 與 C# 應用程式整合的逐步過程,並示範如何使用 IronPDF library 從您的 MySQL 資料庫中的資料生成 PDF。

先決條件

要跟隨本指南,您將需要:

  • Visual Studio 或任何 C# IDE
  • 已安裝並運行的 MySQL 資料庫
  • 用於 PDF 生成的 IronPDF library

設置 MySQL 資料庫

安裝和配置 MySQL

  1. mysql.com 下載最新版本的 MySQL。
  2. 運行安裝程式並按照安裝說明進行操作。 選擇"開發者預設"以包含 MySQL Server 和 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 library(通常稱為 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 資料庫,您可以用對應的 DNS 條目替換伺服器名,此條目解析到資料庫的 IP。

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 的薪資欄位。

使用 IronPDF 從 MySQL 資料生成 PDF

IronPDF介紹

IronPDF 是一個強大的程式庫,允許開發者在 C# 應用程式中輕鬆建立、編輯和操作 PDF 文件。 它支持多種 PDF 功能,使其成為需要自動化報告生成、文件操作或 HTML 到 PDF 轉換的資料驅動應用程式的理想工具。 無論您需要將動態網頁轉換為 PDF 文件,還是從頭開始生成自定義 PDF,IronPDF 都能簡化此過程,只需幾行程式碼。

IronPDF 的關鍵功能

  • HTML 到 PDF 轉換: IronPDF 的一個突出功能是其將 HTML 內容轉換為完全格式化的 PDF 文件的能力。 此功能特別適用於從動態網頁內容生成報告或與儲存在網頁格式中的資料配合使用。
  • 編輯 PDF: IronPDF 允許編輯現有的 PDF,包括新增、移除和修改內容,如文字、圖片、表格等。 這對於需要處理或更新預先存在的文件的應用程式非常理想。
  • PDF 合併和拆分: 使用 IronPDF,您可以輕鬆地合併多個 PDF 為一個單一文件或拆分 一個大型 PDF 為更小的文件。 此功能對於組織和管理大量文件非常有用。
  • 樣式和自定義: 當從 HTML 生成 PDF 時,您可以使用 CSS 來設計文件,從而實現與應用程式設計一致的自定義版面。 IronPDF 給您完全的控制權,以確保您的 PDF 符合特定需求。

在您的 C# 專案中設置 IronPDF

要使用 IronPDF,請通過 Visual Studio 的 NuGet 包管理器進行安裝:

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 注入。
    • 打開連接後 (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#的背景下,什麼是連接池?

連接池指的是從池中重用資料庫連接的做法,通過減少重覆開啟和關閉連接的開銷來提高效率。

如何為C#整合建立一個範例資料庫和表格?

打開MySQL Workbench,連接到您的伺服器,並使用SQL命令如CREATE DATABASE SampleDB;CREATE TABLE Employees (...);來設定範例資料庫和表格。

我應該在C#應用程式的PDF程式庫中尋找什麼功能?

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

如何使用C#對MySQL資料庫執行CRUD操作?

通過在C#中建立一個助手類,使用方法中的參數化SQL命令來在MySQL資料庫中插入、讀取、更新和刪除資料。

如何使用C#更新MySQL資料庫中的員工詳情?

通過在C#中撰寫一個使用參數化UPDATE SQL命令的方法來更新員工詳情,允許基於EmployeeID進行薪水更新等修改。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話