Tuesday 27 February 2018

How to Do Database Connection in Selenium

Sometime in testing we need to validate data in database also or need to extract data from database. There are many type of database availabe now a days like MySQL, SQL, Oracle ect.

In this article we will see how to connect to database and execute query with selenium webdriver.

If we want execute query into database then we have to connect to that database first.

If you are using C# in Selenium then please go to below URL.
How to Do Database Connection in Selenium C#

How to connect to database?

Database would be local or on server also. So we need to first set class for database.

Syntax:

1
2
3
Class.forName("com.mysql.jdbc.Driver"); // For Local

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // For on server

Now we have to connect database.

Syntax:

1
sqlConnection = DriverManager.getConnection("ConnetionString", "Username", "Password"); 

We are done with database connection. Now, we have to execute query on database.

Syntax:


1
2
Statement st = sqlConnection.createStatement();
ResultSet rs = st.executeQuery(vQuery);

You get result of query in object of Resultset. you can use resultset values as per your requirement.Once you are done with your stuff then you have to close database connection.

Syntax:


1
sqlConnection.close();

Please go to below blog for database operation in selenium wrapper automation.

Database Operation with Selenium Wrapper Automation



No comments:

Post a Comment

Popular