Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
Connecting C# applications to MySQL databases enables developers to leverage the power of a relational database for storing, retrieving, and managing data efficiently. This guide provides a step-by-step process to integrate MySQL with C# applications and demonstrates how to generate PDFs from the data within your MySQL database using the IronPDF library.
To follow along with this guide, you’ll need:
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);
For remote access, create a MySQL user with necessary permissions:
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;
Execute the program, and by now it should look like this:
To connect C# applications to MySQL, we use the MySQL Connector/NET library (often referred to as Connector/NET). This is the official .NET driver for MySQL, which can be installed via NuGet.
Open Visual Studio and create a new C# Console Application.
Add the MySql.Data library via NuGet Package Manager:
The following code example demonstrates how to establish a connection to 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}");
}
}
}
In the code above, MySqlConnection is used to establish the connection with the MySQL database.
If your application is hosted in the cloud or requires connecting to a MySQL database via DNS SRV records, you can replace the server name with the corresponding DNS entry that resolves to the database's 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;";
By default, MySQL Connector/NET supports connection pooling, which helps manage database connections more efficiently. Connection pooling reduces the overhead of opening and closing connections repeatedly by reusing existing connections from a pool.
If you want to customize the connection pooling behavior, you can adjust your connection string like this:
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;";
Common issues include incorrect connection strings, firewall restrictions, or MySQL service not running. Ensure all configuration details are correct and that the MySQL service is active.
For code organization, create a DatabaseHelper class to handle all database operations. This class will contain methods for Insert, Read, Update, and Delete data (CRUD) operations.
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();
}
}
}
Explanation
To add new employee data, call the InsertEmployee method:
DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
DatabaseHelper dbHelper = new DatabaseHelper();
dbHelper.InsertEmployee("Alice", "Brown", "Project Manager", 90000);
Retrieve data and display it in the console:
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"]}");
}
}
}
}
Explanation
Here’s an example to update an employee’s 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!");
}
}
Update Command: Uses parameterized query to update the Salary column based on EmployeeID
IronPDF is a robust library that allows developers to easily create, edit, and manipulate PDF documents within C# applications. It supports a wide range of PDF functionalities, making it a perfect tool for data-driven applications that require automated report generation, document manipulation, or HTML-to-PDF conversion. Whether you need to convert dynamic web pages into PDF files or generate custom PDFs from scratch, IronPDF simplifies the process with a few lines of code.
To use IronPDF, install it via NuGet Package Manager in Visual Studio:
Install-Package IronPdf
Install-Package IronPdf
Here’s the full code example that shows how to create a PDF report of employee data:
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!");
}
}
Console Output:
PDF Output
Connection to MySQL Database:
Insert Operation (InsertEmployee):
Read Operation (GetEmployees):
Update Operation (UpdateEmployeeSalary):
PDF Generation (GenerateEmployeeReportPDF):
Collects employee data into an HTML string with a simple table structure.
In this article, we walked through the essential steps for integrating MySQL with a C# application. From setting up the database and performing CRUD operations to generating PDFs with IronPDF, we covered a wide range of foundational topics that are crucial for building data-driven applications. Here's a recap of the major concepts:
By combining C# and MySQL, developers can build robust applications that store and manage data while offering advanced functionalities like PDF reporting. These capabilities are useful across industries, from finance to healthcare, where accurate data management and reporting are critical.
For developers looking to incorporate PDF generation into their C# applications, IronPDF that allows you to test out the full suite of features. Whether you need to generate simple documents or sophisticated reports, IronPDF can be an invaluable tool for automating PDF creation within your workflow.