Monday, 4 August 2014

Connecting to DataBase using Selenium WebDriver


Web Driver cannot directly connect to Database. You can only interact with your Browser using Web Driver. For this we use JDBC("Java Database Connectivity").The JDBC API is a Java API for accessing virtually any kind of tabular data.The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java Virtual Machine.In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do Five things:

1.Load Jdbc driver
Class.forName("com.mysql.jdbc.Driver");

2.Establish a connection with a data source
Connection con =DriverManager.getConnection(dbUrl, userName, password);

3.create Statement Object
Statement stmt = con.createStatement();

4.Send queries and update statements to the data source
ResultSet rs = stmt.executeQuery(query);

5.Process the results
while(rs.next()){

String uName = rs.getString(1);
}

Example Program:

package com.dbconectin;
mport java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class dbConnection {

@Test
public void test() throws ClassNotFoundException, SQLException 
{
try{
//Connection Url
String dbUrl = "jdbc:mysql://localhost:3306/companydb_manf";
//Give Username
String userName ="root";
//Give Password
String password ="root";
//Give Db query
String query = "select * from sr_agritech_estimation_labor where user_id='manager';";

//Load mysql JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Get connection to Db
Connection con =DriverManager.getConnection(dbUrl, userName, password);
//Create Statement Object
Statement stmt = con.createStatement();

//Send Sql query to Db

ResultSet rs = stmt.executeQuery(query);

//While loop to get all data
while(rs.next()){
String uName = rs.getString(1);
String uName1 = rs.getString(2);
String uName2 = rs.getString(3);
String uName3 = rs.getString(4);
String uName4 = rs.getString(5);
System.out.println(uName);
System.out.println(uName1);
System.out.println(uName2);
System.out.println(uName3);
System.out.println(uName4);
System.out.println("-----------------------");
}
//close db connection
con.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

}


}

I guess every one can understand.....;)

No comments:

Post a Comment

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...