Hi Vinod, you can follow these steps to do Database Testing in Selenium Webdriver using JDBC:
1) Make a connection to the Database: In order to make a connection to the database the syntax is
DriverManager.getConnection(URL, "userid", "password" )
Here,
-
Userid is the username configured in the database
-
Password of the configured user
-
URL is of format jdbc:< dbtype>://ipaddress:portnumber/db_name", so for connecting to database with name "emp" in MYSQL, URL will be jdbc:mysql://localhost:3036/emp
And the code to create connection looks like:
Connection con = DriverManager.getConnection(dbUrl,username,password);
You also need to load the JDBC Driver using this line of code:
Class.forName("com.mysql.jdbc.Driver");
2) Send Queries to the Database: Once connection is made, you need to Execute Queries and for that you can use the Statement Object:
Statement stmt = con.createStatement();
Once the statement object is created use the executeQuery method to execute the SQL queries:
stmt.executeQuery(select * from employee;);
3) Process the results: Results from the executed query are stored in the ResultSet Object. Java provides lots of advance methods to process the results. Few of the methods are getString(), getInt(), getDate(), first(), last(), next(), previous() etc.
Following is a sample code snippet to test database using selenium:
Package testDatabase;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnector {
public static void main(String[] args) throws ClassNotFoundException, SQLException { String dbUrl = "jdbc:mysql://localhost:3036/emp"; String username = "root";
String password = "password";
String query = "select * from employee;";
//Load mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");
//Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl,username,password);
//Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs= stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()){
String myName = rs.getString(1);
String myAge = rs.getString(2);
System. out.println(myName+" "+myAge);
}
// closing DB Connection
con.close();
}
}