跳過到頁腳內容
.NET幫助

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

C# MySQL 整合入門

將 C# 應用程式連接至 MySQL 資料庫,可讓開發人員利用關聯式資料庫的強大功能,有效地儲存、擷取及管理資料。 本指南提供將 MySQL 與 C# 應用程式整合的逐步過程,並示範如何使用 IronPDF 函式庫從 MySQL 資料庫內的資料產生 PDF。

先決條件

若要跟進本指南,您需要

  • Visual Studio 或任何 C# IDE
  • MySQL 資料庫(已安裝並執行)
  • IronPDF 函式庫(用於生成 PDF)

設定 MySQL 資料庫

安裝和設定 MySQL。

1.從 mysql.com 下載最新版本的 MySQL。 2.執行安裝程式並遵循設定指示。 選擇"開發者預設"以包括 MySQL Server 和 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)
);

3.插入範例資料:

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# Console Application。 2.透過 NuGet Package Manager 新增 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():執行 select 查詢並傳回 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

更新指令:使用參數化查詢根據員工 ID 更新薪資列。

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

  • 使用參數化查詢(@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 進行諸如薪資更新之類的修改。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

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