1.

How Can You Access A Database From Selenium?

Answer»

Selenium is limited to browser testing. To access databases using Selenium WebDriver we need to use JDBC that is Java Database Connectivity.  JDBC is a SQL level API to execute SQL commands and is responsible for the connection between Java and different databases. So use JDBC Driver to connect to the Database with Selenium when using Java as a programming language.

To connect to the database first download the JDBC jar FILE and add it to your project.

Also you need database URL with port, user ID and password. Syntax in order to make connection to the database is -

DriverManager.getConnection(URL, "userid", "password" )

Where, URL format is  jdbc:<dbtype>://<host>:3036/db_name" and  <dbtype>- database driver. To connect to oracle database <dbtype> will be "oracle"

So for Oracle database with NAME ‘demo’ URL will be jdbc:oracle://<host>:3036/demo

So code for database connection will be

Connection con = DriverManager.getConnection(dbUrl, username, password);

You need to load JDBC driver and code is

Class.forName(“com.oracle.jdbc.Driver”);

Once connection is established you need to execute queries and for that you need to declare STATEMENT object to send queries

Statement stmt = con.createStatement();

Now use the executeQuery method to execute the SQL queries

stmt.executeQuery(“Select * from demo”);

Store the result of executed query in the ResultSet Object

ResultSet rs= stmt.executeQuery(stmt); Import java.sql.Connection; Import java.sql.DriverManager; Import java.sql.ResultSet; Import java.sql.SQLException; Import java.sql.Statement; Import org.testng.annotations.Test; public class TestDatabase { public void TestVerifyDB () { Class.forName ( “Sun.jdbc.odbc.jdbcodbcDriver” ); STRING dblocation = “ C: \\ Users\\Desktop\\DB\\TestDB1.accdb”; Connection con = DriverManager.getConnection ( dbUrl, username, password ); Statement smt = con.createStatement (); ResultSet rs = smt.executeQuery ( “Select*from TestDB1” );


Discussion

No Comment Found