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”


[Test]
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;
//#endregion
SqlConnection SQLConnection = new SqlConnection();
try
{
SQLConnection.ConnectionString = ConnectionString;
SQLConnection.Open();
// You can get the server version
// SQLConnection.ServerVersion
}
catch (Exception Ex)
{
// Try to close the connection
if (SQLConnection != null)
SQLConnection.Dispose();
// 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
return;
}
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
SQLDataAdapter.Fill(dtResult);
// Loop through all entries
foreach (DataRow drRow in dtResult.Rows)
{
// Show a message box with the content of
// the "Name" column
Console.WriteLine(drRow["Employee_no"].ToString());
}
// We don't need the data adapter any more
SQLDataAdapter.Dispose();
SQLConnection.Close();
SQLConnection.Dispose();
selenium.Open("/");
selenium.WaitForPageToLoad("30000");
}

[ad#PostAD]

2 thoughts on “Accessing SQL Database in Selenium C# Script

  1. Ronen says:

    Well done and thank you Pavandeep. This solution worked a treat for me using WebDriver 2.27 and SQL Server Express 2012.

    Regards,
    Ronen.

Leave a Reply

Your email address will not be published. Required fields are marked *