
C# MySQL 连接(开发者用法)
C# MySQL集成介绍
将C#应用程序连接到MySQL数据库,使开发人员能够利用关系数据库的强大功能来高效地存储、检索和管理数据。 本指南提供了一个逐步的过程来将MySQL与C#应用程序集成,并演示如何使用IronPDF库从您的MySQL数据库中的数据生成PDF。
前提条件
要按照本指南进行操作,您需要:
- Visual Studio或任何C# IDE
- 一个MySQL数据库(已安装并运行)
- IronPDF库(用于PDF生成)
设置MySQL数据库
安装和配置MySQL
- 从mysql.com下载MySQL最新版本。
- 运行安装程序并按照设置说明进行操作。 选择"Developer Default"以包括MySQL Server和MySQL Workbench。
- 在设置过程中配置MySQL root用户凭据,并确保MySQL服务正在运行。
创建示例数据库和表
- 打开MySQL Workbench并连接到服务器。
- 使用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)
);
- 插入示例数据:
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安装。
- 打开Visual Studio并创建一个新的C#控制台应用程序。
- 通过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
}
}
}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说明: -**连接字符串:**包含服务器、数据库名称、用户 ID 和密码等详细信息。
- **MySqlConnection:**用于建立连接。
- **Open() 方法:**尝试打开连接。 -**异常处理:**捕获异常以优雅地处理连接错误。
使用DNS SRV记录进行连接(可选)
如果您的应用程序托管在云中或需要通过DNS SRV记录连接到MySQL数据库,您可以将服务器名称替换为解析到数据库IP的相应DNS条目。
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;"连接池
默认情况下,MySQL Connector/NET支持连接池,它有助于更有效地管理数据库连接。 连接池通过重用池中的现有连接,减少反复打开和关闭连接的开销。
如果您想自定义连接池行为,可以这样调整连接字符串:
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;"处理常见错误
常见问题包括错误的连接字符串、防火墙限制或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
}
}
}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说明:
- **参数化:**使用
@Parameter可以降低SQL注入的风险。 - **
connection.Open():**打开 MySQL 连接。 - **
cmd.ExecuteNonQuery():**执行插入查询。
将数据插入MySQL数据库
要添加新的员工数据,请调用InsertEmployee方法:
DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);Dim dbHelper As New DatabaseHelper()
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000)检索和显示数据
检索数据并在控制台中显示:
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说明:
- **
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 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**更新命令:**使用参数化查询根据员工 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包管理器安装它:
将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!");
}
}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(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(firstName As String, lastName As String, position As String, 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(vbCrLf & "Employee List:")
While reader.Read()
Console.WriteLine($"{reader("EmployeeID")} - {reader("FirstName")} {reader("LastName")}, Position: {reader("Position")}, Salary: {reader("Salary")}")
End While
End Using
End Using
End Sub
' Update the salary of an employee
Public Sub UpdateEmployeeSalary(employeeId As Integer, 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()
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>"
End While
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代码分解
-
连接到MySQL数据库:
connectionString定义了MySQL服务器、数据库、用户和密码。- 您可以使用
MySqlCommand处理CRUD操作。
-
插入操作 (InsertEmployee):
- 使用
@LastName等)以防止SQL注入。 - 在打开连接后(
ExecuteNonQuery()运行INSERT SQL语句。
- 使用
-
读取操作 (GetEmployees):
- 执行
SELECT *查询以获取所有员工记录。 - 使用
MySqlDataReader迭代结果集并在控制台中显示每条记录。
- 执行
-
更新操作 (UpdateEmployeeSalary):
- 此方法接受
newSalary以更新员工的工资。 - 它使用参数化的UPDATE SQL查询。
- 此方法接受
-
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自动化创建的宝贵工具。

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。
相关文章


