Database Testing In Selenium
So Database connectivity or Database testing is the most important and frequently used task that we all need to perform in selenium - Data base connectivity.
DB connection is always required to make automation script cover maximum of the task such as validation and verification of data entered or stored in DB.
In Java we can use JDBC driver which help to connect to other db and execute queries and fetch the required data. In Selenium we will take the same approach with JDBC.
Lets see how can we connect to DB in selenium with below code. Before starting if want to know more about selenium click here -> Learn Selenium
JDBC connection ->
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.log4j.Logger;
public class DBr {
static Logger dbLogger= Logger.getLogger(DBHelper.class);
public static Connection getConnection() throws AccountException
{
Connection conn=null;
try {
FileInputStream fin=new FileInputStream("database.properties");
Properties prop= new Properties();
prop.load(fin);
dbLogger.info("Property file loaded..");
System.out.println("properties loaded..");
String driver= prop.getProperty("driver");
String url= prop.getProperty("url");
String user= prop.getProperty("username");
String passwd= prop.getProperty("password");
Class.forName(driver);
conn=DriverManager.getConnection(url,user,passwd);
dbLogger.info("database connected...");
return conn;
} catch (SQLException e) {
dbLogger.error(e.getMessage());
throw new AccountException(e.getMessage());
} catch (FileNotFoundException e) {
dbLogger.error(e.getMessage());
throw new AccountException(e.getMessage());
} catch (IOException e) {
dbLogger.error(e.getMessage());
throw new AccountException(e.getMessage());
} catch (ClassNotFoundException e) {
dbLogger.error(e.getMessage());
throw new AccountException(e.getMessage());
}
}
public long insertAccountHolderDetails(AccountHolder acc)
throws AccountException{
try {
Connection conn= getConnection();
String sql= "insert into AccountHolder values(custId_seq.nextval,?,?,?,?)";
PreparedStatement ps= conn.prepareStatement(sql);
ps.setString(1,acc.getFirstName());
ps.setString(2,acc.getLastName());
ps.setLong(3,acc.getMobilenumber());
ps.setString(4, acc.getAddress());
int rec=ps.executeUpdate();
if(rec==1){
sql= "select custId_seq.currval from abc
ps= conn.prepareStatement(sql);
ResultSet rs= ps.executeQuery();
if(rs.next())
{
long custId= rs.getLong(1);
dbLogger.info("record inserted :" +custId);
return custId;
}
}
} catch (SQLException e) {
dbLogger.error(e.getMessage());
throw new AccountException(e.getMessage());
}
return 0;
}
}