Selenium is compatible with many languages like Java, C#, Python, Perl etc. Connect with database and execute query on database is very common thing in testing.
Basic steps for connect with database and execute query is common for all languages.
Syntax is only difference in different languages. If you are using C# in selenium then please go for below code for database connection and execute query.
I have created one function for database connection and execute query on database. It will return query result into DataTable object.
Code Explanation:
SqlDataAdapter is used for execute query.
Fill command is used for fill query result into DataSet object.
It is for Close and dispose database connection.
In above code, you can see I have return below value.
Basic steps for connect with database and execute query is common for all languages.
- Connect with database
- execute query
- return query result
Syntax is only difference in different languages. If you are using C# in selenium then please go for below code for database connection and execute query.
I have created one function for database connection and execute query on database. It will return query result into DataTable object.
public DataTable GetQueryResult(String vConnectionString, String vQuery) { SqlConnection Connection; // It is for SQL connection DataSet ds = new DataSet(); // it is for store query result try { Connection = new SqlConnection(vConnectionString); // Declare SQL connection with connection string Connection.Open(); // Connect to Database Console.WriteLine("Connection with database is done."); SqlDataAdapter adp = new SqlDataAdapter(vQuery, Connection); // Execute query on database adp.Fill(ds); // Store query result into DataSet object Connection.Close(); // Close connection Connection.Dispose(); // Dispose connection } catch (Exception E) { Console.WriteLine("Error in getting result of query."); Console.WriteLine(E.Message); return new DataTable(); } return ds.Tables[0]; }
Code Explanation:
Connection = new SqlConnection(vConnectionString);
Connection.Open();
It is for connect to database as per you connection string.
Connection string format:
ConnectionString = @"Data Source="Data Source"; Initial Catalog="Database name"; User ID="Username"; Password="Password";
SqlDataAdapter adp = new SqlDataAdapter(vQuery, Connection);
adp.Fill(ds);
SqlDataAdapter is used for execute query.
Fill command is used for fill query result into DataSet object.
Connection.Close(); Connection.Dispose();
It is for Close and dispose database connection.
In above code, you can see I have return below value.
return ds.Tables[0];
It is because, query will give only one table. if your query will return more than
one table then your return type should be DataSet instead of DataTable.
return ds;
Please add comment if you have any question.