.NET 帮助

C# MySQL 连接(面向开发人员的工作原理)

发布 2024年十二月16日
分享:

C# 简介;MySQL 集成

将 C# 应用程序连接到 MySQL 数据库,使开发人员能够利用关系数据库的强大功能有效地存储、检索和管理数据。 本指南提供了一个循序渐进的过程,以整合MySQL本书将介绍如何使用 C# 应用程序生成 PDF 文件,并演示如何通过 MySQL 数据库中的数据使用IronPDF 库.

先决条件

要学习本指南,您需要

  • Visual Studio 或任何 C# IDE
  • MySQL 数据库(已安装并运行)
  • IronPDF 库(用于生成 PDF)

设置 MySQL 数据库

安装和配置 MySQL

  1. 从以下网址下载最新版本的 MySQLmysql.com.

  2. 运行安装程序并按照设置说明进行操作。 选择 "开发人员默认设置 "以包括 MySQL Server 和 MySQL Workbench。

  3. 在设置过程中配置 MySQL 根用户凭据,并确保 MySQL 服务正在运行。

创建示例数据库和表格

  1. 打开 MySQL 工作台并连接到服务器。

  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)
);
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)
);
CREATE DATABASE SampleDB
Dim SampleDB As USE
CREATE TABLE Employees(EmployeeID INT PRIMARY KEY AUTO_INCREMENT, FirstName VARCHAR(50), LastName VARCHAR(50), Position VARCHAR(50), Salary [DECIMAL](10, 2))
VB   C#
  1. 插入示例数据:
INSERT INTO Employees (FirstName, LastName, Position, Salary) 
VALUES ('John', 'Doe', 'Software Developer', 80000),
       ('Jane', 'Smith', 'Data Analyst', 75000);
INSERT INTO Employees (FirstName, LastName, Position, Salary) 
VALUES ('John', 'Doe', 'Software Developer', 80000),
       ('Jane', 'Smith', 'Data Analyst', 75000);
INSERT INTO Employees(FirstName, LastName, Position, Salary) VALUES( 'John', 'Doe', 'Software Developer', 80000), ('Jane', 'Smith', 'Data Analyst', 75000);
VB   C#

为远程访问设置 MySQL 用户(可选)

要进行远程访问,请创建一个具有必要权限的 MySQL 用户:

CREATE USER 'remoteUser'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON SampleDB.* TO 'remoteUser'@'%';
FLUSH PRIVILEGES;
CREATE USER 'remoteUser'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON SampleDB.* TO 'remoteUser'@'%';
FLUSH PRIVILEGES;
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'CREATE USER 'remoteUser"@"c%' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES @ON SampleDB.* @TO 'remoteUser"@"c%'; FLUSH PRIVILEGES;
VB   C#

执行程序,现在它应该是这样的:

C# MySQL 连接(开发人员如何使用):图 1

将 C## 连接到 MySQL 数据库

在 C# 中安装 MySql.Data 库;

为了将 C# 应用程序连接到 MySQL,我们使用了 MySQL Connector/NET 库(通常称为 Connector/NET). 这是 MySQL 的官方 .NET 驱动程序,可通过 NuGet 安装。

  1. 打开 Visual Studio 并创建一个新的 C# 控制台应用程序。

    1. 通过 NuGet 包管理器添加 MySql.Data 库:

      • 右键单击项目 > 管理 NuGet 软件包 > 浏览 > 搜索 MySql.Data 并安装。

    C# MySQL 连接(开发人员如何使用):图 2 - 从 NuGet 软件包管理器安装 MySql.Data

编写连接代码

下面的代码示例演示了如何建立与 MySQL 的连接:

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}");
        }
    }
}
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}");
        }
    }
}
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}")
		End Try
	End Sub
End Class
VB   C#

C# MySQL 连接(开发人员如何使用):图 3 - 控制台输出:连接成功

说明

  • private string server:代表主机(例如,本地主机用于本地服务器或用于远程连接的 IP 地址).
  • private string database:代表数据库名称(本例中的 SampleDB).
  • 私人字符串密码:用于验证 MySQL 用户身份的密码。
  • private MySqlConnection connection:MySQL 连接对象,用于打开和管理连接。

    在上面的代码中,MySqlConnection 用于与 MySQL 数据库建立 连接。

使用 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;"
VB   C#

连接池

默认情况下,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;"
VB   C#

处理常见错误

常见问题包括连接字符串不正确、防火墙限制或 MySQL 服务未运行。 确保所有配置细节正确无误,MySQL 服务处于活动状态。

使用 C# 和 MySQL 执行 CRUD 操作

创建用于数据库操作的 C# 类

在代码组织方面,创建一个 DatabaseHelper 类来处理所有数据库操作。 该类将包含插入、读取、更新和删除数据的方法(CRUD)业务。

public class DatabaseHelper
{
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";
    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();
        }
    }
}
public class DatabaseHelper
{
    private string connectionString = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;";
    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();
        }
    }
}
Public Class DatabaseHelper
	Private connectionString As String = "Server=localhost;Database=SampleDB;User ID=root;Password=yourpassword;"
	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()
		End Using
	End Sub
End Class
VB   C#

说明

  • 参数化:使用 @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)
VB   C#

检索和显示数据

检索数据并在控制台中显示:

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
VB   C#

说明

  • 执行阅读器():执行选择查询并返回 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);
        cmd.Parameters.AddWithValue("@Salary", newSalary);
        cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
        connection.Open();
        cmd.ExecuteNonQuery();
        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);
        cmd.Parameters.AddWithValue("@Salary", newSalary);
        cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
        connection.Open();
        cmd.ExecuteNonQuery();
        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)
		cmd.Parameters.AddWithValue("@Salary", newSalary)
		cmd.Parameters.AddWithValue("@EmployeeID", employeeId)
		connection.Open()
		cmd.ExecuteNonQuery()
		Console.WriteLine("Employee salary updated successfully!")
	End Using
End Sub
VB   C#

更新命令:使用参数化查询,根据雇员 ID 更新薪金列

使用 IronPDF 从 MySQL 数据生成 PDF 文件

IronPDF 简介

IronPDFC# PDF 是一个强大的库,允许开发人员在 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
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

将 MySQL 数据转换为 PDF 格式

以下是完整的代码示例,展示了如何创建员工数据的 PDF 报告:

using IronPdf;
using System;
using MySql.Data.MySqlClient;
public class Program
{
    // MySQL connection string
    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 IronPdf;
using System;
using MySql.Data.MySqlClient;
public class Program
{
    // MySQL connection string
    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 IronPdf
Imports System
Imports MySql.Data.MySqlClient
Public Class Program
	' MySQL connection string
	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
VB   C#

控制台输出:

C# MySQL 连接(开发人员如何使用):图 4

PDF 输出

C# MySQL 连接(开发人员如何使用):图 5

代码分解

  1. 与 MySQL 数据库的连接:

    • connectionString 定义了 MySQL 服务器、数据库、用户和密码。
    • 您可以使用 MySqlConnection 进行连接,并使用 MySqlCommand 处理 CRUD 操作。
  2. 插入操作(插入员工):

    • 使用带有参数化查询的 MySqlCommand(@名、@姓等。)防止 SQL 注入。
    • 打开连接后(connection.Open()).NET、Java、Python 或 Node.js()运行 INSERT SQL 语句。
  3. 阅读操作(获取员工):

    • 执行 SELECT * 查询以获取所有员工记录。
    • 使用 MySqlDataReader 遍历结果集,并在控制台中显示每条记录。
  4. 更新操作(更新员工工资):

    • 该方法接受 employeeId 和 newSalary,用于更新员工的薪资。
    • 它使用参数化 UPDATE SQL 查询。
  5. PDF生成(生成员工报告 PDF):**

    • 将员工数据收集到具有简单表格结构的 HTML 字符串中。

    • HTML 内容将传递给 IronPDF 的 HtmlToPdf.StaticRenderHtmlAsPdf 方法,以生成 PDF 报告。
    • 生成的 PDF 文件保存为 EmployeeReport.pdf。

结论

在本文中,我们介绍了将 MySQL 与 C# 应用程序集成的基本步骤。 从设置数据库、执行 CRUD 操作到使用 IronPDF 生成 PDF,我们涵盖了对构建数据驱动型应用程序至关重要的各种基础主题。 以下是主要概念的概述:

  • MySQL 和 C# 集成:我们演示了如何使用 MySql.Data 库连接到 MySQL 数据库、管理数据库连接以及使用参数化查询执行 CRUD 操作。 这将确保数据能够以安全、有序的方式高效地存储、更新和检索。
  • 执行 CRUD 操作:通过插入、更新和读取员工数据的示例方法,您可以扩展这一逻辑来管理现实世界数据库中的其他类型记录。 使用参数化查询还有助于减轻 SQL 注入攻击,确保应用程序的安全性。
  • 用于生成 PDF 的 IronPDF:IronPDF 可让您轻松地从动态 HTML 内容生成具有专业外观的 PDF。 通过将从 MySQL 检索到的数据转换为 HTML 表格,我们可以创建自定义报告并将其保存为 PDF,这对于生成发票、报告、摘要等非常有用。 IronPDF 简单明了的 API 使其成为任何需要在应用程序中处理 PDF 生成的 C# 开发人员的绝佳工具。

    通过结合 C# 和 MySQL,开发人员可以构建强大的应用程序,用于存储和管理数据,同时提供 PDF 报告等高级功能。 这些功能在各行各业都很有用,从金融到医疗保健,准确的数据管理和报告都至关重要。

    适用于希望将 PDF 生成功能纳入其 C# 应用程序的开发人员、IronPDF您还可以通过该工具测试全套功能。 无论您需要生成简单的文档还是复杂的报告,IronPDF 都是您在工作流程中自动创建 PDF 的宝贵工具。

< 前一页
Parseint C#(开发人员工作原理)
下一步 >
C# 命名元组(如何为开发人员工作)