Accessing SQL Database in Selenium C# Script

Here is an example that shows you how you can connect to the database and how to execute the SQL queries in the selenium C# scripts.
In this example I am connecting the SQL server by passing the server name, username password and the database name. I then execute the SQL command “select Employee_no from employee where deptno =100”

public void SQLTest()
//#region Building the connection string
string Server = "ServerName";
string Username = "username";
string Password = "password";
string Database = "DatabaseName";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = ConnectionString;
// You can get the server version
// SQLConnection.ServerVersion
catch (Exception Ex)
// Try to close the connection
if (SQLConnection != null)
// Create a (useful) error message
string ErrorMessage = "A error occurred while trying to connect to the server.";
ErrorMessage += Environment.NewLine;
ErrorMessage += Environment.NewLine;
ErrorMessage += Ex.Message;
// Show error message (this = the parent Form object)
Console.WriteLine(ErrorMessage + "Connection error.");
// Stop here
string SQLStatement = "select Employee_no from employee where deptno =100";
// Create a SqlDataAdapter to get the results as DataTable
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection);
// Create a new DataTable
DataTable dtResult = new DataTable();
// Fill the DataTable with the result of the SQL statement
// Loop through all entries
foreach (DataRow drRow in dtResult.Rows)
// Show a message box with the content of
// the "Name" column
// We don't need the data adapter any more