在生產環境中測試無浮水印。
在任何需要的地方都能運作。
獲得30天完全功能的產品。
幾分鐘內即可啟動並運行。
試用產品期間完全訪問我們的支援工程團隊
將 C# 應用程式連接至 MySQL 資料庫,使開發人員能夠利用關聯式資料庫的強大功能,高效地儲存、檢索和管理資料。 本指南提供了逐步整合的過程MySQL與 C# 應用程式結合,展示如何使用您 MySQL 資料庫中的數據生成 PDF。IronPDF 庫.
要了解此指南,您需要:
從下載最新版本的 MySQLmysql.com.
運行安裝程式並按照設置指示操作。 選擇「開發者預設」以包含 MySQL Server 和 MySQL Workbench。
打開 MySQL Workbench 並連接到伺服器。
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)
);
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);
要進行遠端存取,請建立一個具有必要許可權的 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;
執行程式,現在它應該看起來像這樣:
為了將 C# 應用程式連接到 MySQL,我們使用 MySQL Connector/NET 函式庫。(通常稱為 Connector/NET). 這是 MySQL 的官方 .NET 驅動程式,可以通過 NuGet 安裝。
開啟 Visual Studio 並建立新的 C# 主控台應用程式。
透過 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}");
}
}
}
private MySqlConnection connection: 一個用來開啟和管理連線的 MySQL connection 物件。
在上面的代碼中,使用 MySqlConnection 來建立與 MySQL 資料庫的連接。
如果您的應用程式託管在雲端或需要透過 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;";
預設情況下,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;";
常見問題包括不正確的連接字串、防火牆限制或 MySQL 服務未運行。 確保所有配置詳細資訊正確且 MySQL 服務處於啟用狀態。
為了更好的程式碼組織,創建一個 DatabaseHelper 類別來處理所有資料庫操作。 此類別將包含插入、讀取、更新和刪除資料的方法(增刪改查)運作。
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();
}
}
}
說明
要新增員工數據,請調用 InsertEmployee
方法:
DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
DatabaseHelper dbHelper = 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 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 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!");
}
}
更新命令:使用參數化查詢根據 EmployeeID 更新 Salary 欄位
IronPDF是一個強大的程式庫,允許開發人員在 C# 應用程式中輕鬆創建、編輯和操作 PDF 文件。 它支持各種 PDF 功能,是資料驅動應用程式的完美工具,適合需要自動化報告生成、文件操作或 HTML 到 PDF 轉換的需求。 無論您是需要將動態網頁轉換為 PDF 檔案,還是從頭開始生成自訂 PDF,IronPDF 只需幾行代碼即可簡化這一過程。
使用IronPDF,通過 Visual Studio 中的 NuGet 套件管理器安裝:
Install-Package IronPdf
以下是顯示如何建立員工資料 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!");
}
}
控制台輸出:
PDF 輸出
連接到 MySQL 資料庫:
插入操作(插入員工)
讀取操作(獲取員工)
更新操作(更新員工薪水)
PDF 生成(GenerateEmployeeReportPDF)
將員工資料收集成具有簡單表格結構的 HTML 字串。
在本文中,我們介紹了將 MySQL 與 C# 應用程式整合的基本步驟。 從設置資料庫和執行 CRUD 操作到使用 IronPDF 生成 PDF,我們涵蓋了建立資料驅動應用程式所需的廣泛基礎主題。 以下是主要概念的回顧:
IronPDF for PDF Generation:IronPDF 讓從動態 HTML 內容生成專業外觀的 PDF 變得簡單。 透過將從 MySQL 擷取的資料轉換為 HTML 表格,我們可以建立自訂報告並將其儲存為 PDF,這對於生成發票、報告、摘要等非常有用。 IronPDF 的簡單 API 使其成為任何需要在應用程式中處理 PDF 生成的 C# 開發人員的優秀工具。
透過結合 C# 和 MySQL,開發人員可以構建強大的應用程式,這些應用程式不僅能儲存和管理數據,還能提供如 PDF 報告等高級功能。 這些功能在各個行業中都很有用,從金融到醫療保健,精確的數據管理和報告都是至關重要的。
對於希望將 PDF 生成整合到其 C# 應用程式中的開發人員,IronPDF允許您測試完整功能套件。 無論您需要生成簡單的文件還是複雜的報告,IronPDF 都可以成為在您的工作流程中自動化 PDF 創建的寶貴工具。