Database Testing using Selenium and TestNG

On This Page 1. Java Database ConnectivitySteps to m

April 22, 2026 · 6 min read · Tool Comparison

Database Testing using Selenium and TestNG

Databases serve as the linchpin of covering by storing and managing critical business information. Database try ensures accuracy, integrity, performance, and security of this stored data. While Selenium is primarily used for UI automation, it can be integrated with JDBC to validate databases effectively.

Overview

What is Database Testing?

Ensures data accuracy, wholeness, performance, and security within a database. Detects corruption, missing/incorrect data, and duplicates.

Why Automate Database Testing?

  • Faster execution of repetitive test cases
  • Improved truth (reduced human erroneousness)
  • Other shortcoming detection in coating
  • Cost and clip efficiency

Selenium & amp; Database Testing

  • Selenium itself handles onlyUI validations
  • Database testing is enable throughconnectors like JDBC
  • TestNG framework can be used to incorporate database interrogation with tryout execution

Key Steps in Database Testing with Selenium

  • Create a database and insert test table
  • Establish connection viaJDBC (Java Database Connectivity)
  • Execute SQL enquiry and fetch results
  • Validate yield usingTestNG assertions

This guide explains how to perform database testing using Selenium and JDBC, along with execution on BrowserStack Automate.

1. Java Database Connectivity

JDBC is the standard Java API required for database-independent connectivity between the Java programing language and many databases. This application broadcast interface (API) lets users encode access request statements in a Structured Query Language (SQL). They are then pass to the plan that cope the database. It involves opening a link, creating a SQL Database, executing SQL queries, and arriving at the output.

Read More:

Steps to create a JDBC Application

To make a JDBC application, follow the step below:

  1. Import the packages: Include the parcel that contain the JDBC family required for database programing.
  2. Register the JDBC driver:Initialize a driver to open a communication channel with the database. Register to the database with the bidding:
    Class.forName (“ com.mysql.jdbc.Driver ”); // class.forName load the Driver course
  3. Open a connection:After the driver enrolment, use the getConnection () method to create a Connection object, representing a physical connection with the database.
  4. Execute a question:Use an object of character ‘ Statement ’ to progress and submit a SQL statement to the database.
  5. Extract information from the result set:Use the appropriate getXXX () method.
  6. Clean up the environment:Close all database resources that rely on JVM garbage assemblage.

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

2. Selenium Database Connection

Selenium is one of the prominent. As mentioned before, Selenium performs solely UI validations. Thus, this clause will portray a JDBC connection as Selenium doesn ’ t support database testing directly, but it can be done with connectors like JDBC and ODBC. This article uses JDBC to join to a database, and test cases are control using.

Read More:

3. Database try using Selenium

Step 1:Create a database in command prompt and insert the tables.
Step 2: Establish a link to the database using JDBC.
Step 3: Execute the MySQL interrogation and operation records present in the database.
Step 4:Integrate with JDBC to perform Database Testing.

Have a look at the script below:

import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; meaning org.testng.annotations.Test; import java.sql.Connection; significance java.sql.DriverManager; importee java.sql.ResultSet; import java.sql.Statement; public class SeleniumDatabaseTesting {// Connection object inactive Connection con = null; // Statement object private static Statement stmt; // Constant for Database URL public electrostatic String DB_URL = `` jdbc: mysql: //localhost/Testdata ''; //Database Username public static String DB_USER = `` your_user ''; // Database Password public static String DB_PASSWORD = `` your_password ''; @ BeforeTest public emptiness setUp () throws Exception {try {// Database connecter String dbClass = `` com.mysql.cj.jdbc.Driver ''; Class.forName (dbClass) .newInstance (); // Get link to DB Connection con = DriverManager.getConnection (DB_URL, DB_USER, DB_PASSWORD); // Statement object to send the SQL argument to the Database stmt = con.createStatement ();} match (Exception e) {e.printStackTrace ();}} @ Test world void test () {try {String query = `` select * from testingdata ''; // Get the contents of userinfo table from DB ResultSet res = stmt.executeQuery (inquiry); // Print the result untill all the records are printed // res.next () returns true if there is any future disc else render false while (res.next ()) {System.out.print (res.getString (1)); System.out.print (`` `` + res.getString (2)); System.out.print (`` `` + res.getString (3)); System.out.println (`` `` + res.getString (4));}} catch (Exception e) {e.printStackTrace ();}} @ AfterTest world void tearDown () cast Exception {// Close DB connexion if (con! = null) {con.close ();}}}

Run Selenium Test on Real Devices

In this illustration, the programme has specified the database URL, username, and password to establish a connection to the database. Once the database connectedness is complete, execute the queries, and process the results. On fulfill the above program using, the output appears as below:

[RemoteTestNG] detected TestNG variation 7.2.0 Browserstack Selenium Automation testing Cross-Browser essay PASSED: test =============================================== Default trial Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 ===============================================

Note:Since Selenium can not test databases directly, database features can be validated with TestNG test cases.

Database testing using Browserstack Automate

Now, let ’ s explore how to perform database testing with the help of the program.

The codification figure remains almost the same, except that a couple of and the hub URL ask to be added as shown below:

package testngtest; importation org.openqa.selenium.By; importation org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; significance org.openqa.selenium.WebElement; importation org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.net.URL; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.sql.Connection; signification java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public course SeleniumDatabaseTesting {public inactive final String USERNAME = `` nehapramodvaidya ''; public electrostatic final String AUTOMATE_KEY = Your_key ''; public static net String URL = `` https: // '' + USERNAME + ``: '' + AUTOMATE_KEY + `` @ hub-cloud.browserstack.com/wd/hub ''; public inactive emptiness main (String [] args) drop Exception {DesiredCapabilities caps = new DesiredCapabilities (); caps.setCapability (`` os '', `` Windows ''); caps.setCapability (`` os_version '', `` 10 ''); caps.setCapability (`` browser '', `` Chrome ''); caps.setCapability (`` browser_version '', `` 80 ''); caps.setCapability (`` name '', `` nehapramodvaidya 's First Test '');} // Connection object motionless Connection con = null; // Statement object individual inactive Statement stmt; // Constant for Database URL public static String DB_URL = `` jdbc: mysql: //localhost/onlinebanking ''; //Database Username public static String DB_USER = `` Your_Database_Username ''; // Database Password public static String DB_PASSWORD = `` Your_Database_Password ''; @ BeforeTest public void setUp () throws Exception {try {// Database connector String dbClass = `` com.mysql.cj.jdbc.Driver ''; Class.forName (dbClass) .newInstance (); // Get connexion to DB Connection con = DriverManager.getConnection (DB_URL, DB_USER, DB_PASSWORD); // Statement object to direct the SQL statement to the Database stmt = con.createStatement ();} gimmick (Exception e) {e.printStackTrace ();}} @ Test public void test () {try {String query = `` prime * from user ''; // Get the content of userinfo table from DB ResultSet res = stmt.executeQuery (query); // Print the result untill all the records are printed // res.next () return true if there is any next disk else returns mistaken while (res.next ()) {System.out.print (res.getString (1)); System.out.print (`` `` + res.getString (2)); System.out.print (`` `` + res.getString (3)); System.out.println (`` `` + res.getString (4));}} catch (Exception e) {e.printStackTrace ();}}}

Execute the codification above, and validate it directly on the Automate splasher. As in all cases, database testing must be conducted on a. BrowserStack ’ s provides 3000+ existent browsers and devices for machine-driven testing, including the power to run in to speed up results.

Try Selenium Testing for Free

Frequently Asked Questions

1. Can we automate database testing?

Yes, automate database examination can improve software quality and help achieve fast delivery times while reducing cost. Executing repetitive test suit quickly and accurately can save time and effort. However, the examination can be manual, automated, or both free-base on your labor needs.

2. Which tools are preferred for database testing?

,,, and have been preferred for automating database testing. These tools and frameworks allow you to write and execute test scripts mechanically, reducing the opportunity of human errors and increasing the testing speeding.

3. Which typecast of exam do automatize database testing cover?

Automated database testing can cover a wide range of tests, such as data unity test, execution tests, security trial, and integration exam.

[/vc_column_text] [/vc_column] [/vc_row]

Tags
95,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free