database-testing-C#-banner-image
Database Connectivity Selenium With C# Test Automation

How to Connect MySQL Database with Selenium Tests in C#

Integrating MySQL with Selenium in C# enhances your automation framework by enabling real-time backend validations. This allows test scripts to fetch test data, validate UI elements against database records, and ensure that backend logic is functioning correctly.

Using the MySql.Data.MySqlClient library, testers can establish connections, run SQL queries, and ensure data-driven, dynamic testing. This means instead of relying on static values, tests can retrieve actual usernames and encrypted passwords from the database, verify form submissions, and confirm record updates. The result? More reliable, robust, and production-ready automation.

Why This Matters

Most automation tests focus only on the UI clicking buttons and verifying that elements appear correctly. However, many real-world issues occur beneath the surface in the database or business logic layer. By connecting Selenium to your database, you move beyond superficial validations.

You’re no longer just confirming that a login button was clicked, you’re validating that the user’s credentials exist and were authenticated in the database. Instead of assuming a form submission worked, you query the database to ensure the data was actually saved and is accurate.

This approach transforms your tests into data-driven, real-time, and reliable verifications. It bridges the gap between front-end behavior and back-end integrity, ensuring your software behaves exactly as expected across all layers. If you want robust, production-ready automation, integrating database validation is a must.

Architecture Overview

Below is a high-level architecture diagram that outlines the flow of data between your C# test automation framework, MySQL databases, and the web application.

Setting Up the Environment

Required NuGet Packages

Install the following packages using NuGet Package Manager in Visual Studio:

  • Selenium.WebDriver
  • Selenium.WebDriver.ChromeDriver
  • MySql.Data (for MySQL connectivity)

Database Setup

We’ll use two MySQL databases:

  • classicmodels: Contains customer information such as names and countries.
  • UserDB: Stores login credentials (email + encrypted password).

Example table creation for UserDB:

CREATE DATABASE UserDB;
USE UserDB;

CREATE TABLE Users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

SELECT * FROM Users;

Use MySQL Workbench to create these databases, manage schemas, and insert test data using AES_ENCRYPT() for realistic login scenarios.

Connecting C# Selenium with MySQL

Connection Strings

Define connection strings in your code:

// classicmodels database
string connectionString1 = "Server=localhost;Port=3306;Database=classicmodels;User Id=root;Password=JigNect@123;";

// UserDB database
string connectionString2 = "server=localhost;port=3306;database=UserDB;user=root;password=JigNect@123;";

Establishing the Connection

con = new MySqlConnection(connectionString);
con.Open();
Console.WriteLine("Connected to MySQL database!");

Using MySqlCommand & Reader

string query = "SELECT customerName, country FROM customers";
cmd = new MySqlCommand(query, con);
reader = cmd.ExecuteReader();

To get scalar values:

string countQuery = "SELECT COUNT(*) FROM customers WHERE country = 'USA'";
cmd = new MySqlCommand(countQuery, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());

Using SQL Data in Selenium Tests

Dynamic Login with DB Credentials

Retrieve user credentials and automate login:

private void PerformLogin()
{
IWebDriver driver = new ChromeDriver();

try
{
    driver.Navigate().GoToUrl("https://magento.softwaretestingboard.com/customer/account/login/");
    driver.Manage().Window.Maximize();

    driver.FindElement(By.Id("email")).SendKeys(email);
    driver.FindElement(By.Id("pass")).SendKeys(password);
    driver.FindElement(By.Id("send2")).Click();

    Thread.Sleep(5000);
    Console.WriteLine("Login Attempted!");
}
catch (Exception ex)
{
    Console.WriteLine("Error during login process: " + ex.Message);
}
finally
{
    driver.Quit();
}

}

demo-login-page-image

Verifying UI Data Against Database

After login, validate that UI details match database entries:

public void RunAutomation()
{
    GetUserCredentials();

    if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
    {
        PerformLogin();
    }
    else
    {
        Console.WriteLine("No valid credentials found in database.");
    }
}

NOTE :- We use this code because the database utilizes hashing for password encryption, ensuring that neither developers nor anyone else can misuse it.

sql-data-image
private void GetUserCredentials()
{
    string connectionString = "server=localhost;port=3306;database=UserDB;user=root;password=JigNect@123;";

    // Decrypt the password using AES_DECRYPT
    string query = "SELECT email, CAST(AES_DECRYPT(password_hash, @Key) AS CHAR) AS decrypted_password FROM Users WHERE email = 'harsh@gmail.com';";

    try
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            connection.Open();
            Console.WriteLine("Connected to MySQL database!");

            using (var command = new MySqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@Key", EncryptionKey);

                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        email = reader.GetString("email");

                        // Check for NULL password
                        if (!reader.IsDBNull(reader.GetOrdinal("decrypted_password")))
                        {
                            password = reader.GetString("decrypted_password");
                            Console.WriteLine($"Retrieved Credentials - Email: {email}, Password: {password}");
                        }
                        else
                        {
                            Console.WriteLine("Decrypted password is NULL. Check encryption key!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No user found with the given email.");
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error connecting to database: " + ex.Message);
    }
}

Assertions Based on Backend Validation

After a UI action, verify that backend is updated:

string query = "SELECT COUNT(*) FROM customers WHERE country = 'USA'";
cmd = new MySqlCommand(query, con);
int countUSA = Convert.ToInt32(cmd.ExecuteScalar());

Console.WriteLine($"Customers from USA: {countUSA}");

if (countUSA <= 10)
    throw new Exception("There should be more than 10 customers from the USA!");

Closing the Connection

Always close database connections using a finally block:

finally
{
    if (reader != null) reader.Close();
    if (cmd != null) cmd.Dispose();
    if (con != null) con.Close();
    Console.WriteLine("Database connection closed.");
}
  • reader.Close() → Releases the data reader
  • cmd.Dispose() → Frees up SQL command resources
  • con.Close() → Properly shuts down the DB connection

Conclusion

By connecting C# & Selenium with MySQL, you bridge the gap between UI validation and backend verification. This powerful integration allows your tests to fetch live data, validate real-world scenarios, and assert backend integrity all within your automation framework.

Whether you’re verifying login flows, customer records, or transactional behavior, database-driven testing offers unmatched reliability. Combined with good connection management and dynamic assertions, your test suite becomes robust, adaptive, and production-ready.

Witness how our meticulous approach and cutting-edge solutions elevated quality and performance to new heights. Begin your journey into the world of software testing excellence. To know more refer to Tools & Technologies & QA Services.

If you would like to learn more about the awesome services we provide,  be sure to reach out.

Happy Testing 🙂