Popular Searches
Popular Course Categories
Popular Courses

Database Connectivity

Database Connectivity

API & Database Integration

Database Connectivity in Selenium Automation Testing

Database Connectivity is the process of connecting an automation framework to a database so that test scripts can read, insert, update, or validate data stored in the database. In Selenium automation testing, database connectivity is commonly implemented using Java Database Connectivity (JDBC).

Database connectivity is especially useful when test data is stored in a relational database instead of being hard-coded inside automation scripts. A Selenium framework can retrieve usernames, product details, order information, customer records, expected results, or other test data directly from a database and use that information during test execution.

Database validation can also be used to verify whether an action performed through the web application has correctly updated the backend database. For example, after creating a new customer through a web application, an automation test can query the database and verify that the customer record was successfully created.

Course Resource: Selenium Training | Register for Course Demo


1. What is Database Connectivity?

Database connectivity allows a Java application or automation framework to communicate with a database. Through a database connection, the framework can execute SQL queries and process the results returned by the database.

In Selenium automation, database connectivity is normally handled separately from browser automation. Selenium interacts with the user interface, while JDBC is responsible for communicating with the database.

TestNG Test

    |

    v

Selenium WebDriver

    |

    v

Web Application

    |

    v

Application Backend

    |

    v

Database

 

JDBC

    |

    +---- Connect to Database

    +---- Execute SQL Query

    +---- Read Result

    +---- Validate Data


2. Why is Database Connectivity Important?

Modern applications store a large amount of information in databases. UI testing alone may not always be sufficient to verify whether the correct backend operation occurred.

  • Validates data created through the UI.
  • Reads test data dynamically.
  • Verifies database records after UI operations.
  • Supports data-driven testing.
  • Reduces hard-coded test data.
  • Helps validate end-to-end workflows.
  • Allows automation frameworks to interact with backend data.
  • Supports database-based test setup and cleanup.
  • Helps verify application-to-database integration.
  • Can be combined with Selenium, TestNG, Maven, and Page Object Model.


3. Database Connectivity in Selenium

Selenium itself does not provide database connectivity. Selenium WebDriver is designed primarily for browser automation. Java database connectivity is normally implemented using JDBC or a database-specific library.

TechnologyPurpose
Selenium WebDriverAutomates the browser and web application
JavaProgramming language used for the automation framework
JDBCConnects Java applications to databases
SQLQueries and manipulates database data
TestNGManages test execution and assertions
MavenManages project dependencies and builds


4. What is JDBC?

JDBC (Java Database Connectivity) is a standard Java API used to connect Java applications with databases.

JDBC provides interfaces and classes that allow Java programs to establish database connections, execute SQL statements, retrieve results, and manage database resources.

Java Automation Framework

          |

          v

        JDBC

          |

          v

    JDBC Driver

          |

          v

      Database


5. JDBC Architecture

A typical JDBC architecture consists of the Java application, JDBC API, database driver, and database server.

Automation Test

      |

      v

   JDBC API

      |

      v

 JDBC Driver

      |

      v

Database Server

      |

      v

Database

The JDBC driver acts as the communication layer between the Java application and the specific database.


6. Common Databases Used in Automation Testing

DatabaseTypical JDBC DriverCommon Usage
MySQLMySQL Connector/JWeb applications and test environments
PostgreSQLPostgreSQL JDBC DriverEnterprise and web applications
OracleOracle JDBC DriverEnterprise applications
SQL ServerMicrosoft JDBC DriverMicrosoft-based applications
H2H2 JDBC DriverTesting and lightweight applications


7. Database Connectivity Flow

Start Test

    |

    v

Load Database Driver

    |

    v

Create Database Connection

    |

    v

Create Statement / PreparedStatement

    |

    v

Execute SQL Query

    |

    v

Receive ResultSet

    |

    v

Read Database Data

    |

    v

Compare with Expected Data

    |

    v

TestNG Assertion

    |

    v

Close Database Resources

    |

    v

End Test


8. JDBC Connection Steps

The general process for JDBC database connectivity is:

  1. Add the appropriate JDBC driver dependency.
  2. Define the database URL.
  3. Define the database username.
  4. Obtain a database connection.
  5. Create a Statement or PreparedStatement.
  6. Execute the SQL query.
  7. Read the ResultSet.
  8. Perform validation or processing.
  9. Close database resources.


9. JDBC Connection URL

The JDBC URL identifies the database server, port, database name, and sometimes additional connection properties.

String url = "jdbc:mysql://localhost:3306/testdb";

String username = "root";

String password = "password";

 

Connection connection =

        DriverManager.getConnection(url, username, password);

The exact JDBC URL format depends on the database being used.


10. Required JDBC Imports

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.PreparedStatement;

import java.sql.SQLException;


11. Creating a Database Connection

A connection can be created using DriverManager.getConnection().

String url = "jdbc:mysql://localhost:3306/testdb";

String username = "root";

String password = "password";

 

Connection connection =

        DriverManager.getConnection(url, username, password);

 

System.out.println("Database connected successfully");


12. Checking Database Connection

if (connection != null && !connection.isClosed()) {

    System.out.println("Connection is active");

}

Checking the connection can be useful during framework debugging.


13. Creating a Statement

A Statement object can be used to execute SQL statements.

Statement statement = connection.createStatement();

 

ResultSet resultSet =

        statement.executeQuery("SELECT * FROM users");

For dynamic values, PreparedStatement is generally preferred because it provides parameter binding and helps avoid SQL injection risks.


14. Executing a SELECT Query

The executeQuery() method is commonly used for SELECT statements.

String query = "SELECT * FROM users";

 

Statement statement = connection.createStatement();

ResultSet resultSet = statement.executeQuery(query);


15. Understanding ResultSet

ResultSet represents the data returned by a database SELECT query.

while (resultSet.next()) {

    String username = resultSet.getString("username");

    String email = resultSet.getString("email");

 

    System.out.println(username);

    System.out.println(email);

}

The next() method moves the cursor to the next row.


16. Reading Different Data Types

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

double salary = resultSet.getDouble("salary");

boolean active = resultSet.getBoolean("active");

The getter method should correspond to the database column's data type.


17. Reading Data by Column Index

ResultSet values can also be retrieved by column index.

String name = resultSet.getString(2);

int age = resultSet.getInt(3);

Column names are generally easier to maintain and understand than numeric indexes.


18. Complete Basic JDBC Example

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

 

public class DatabaseExample {

 

    public static void main(String[] args) {

 

        String url = "jdbc:mysql://localhost:3306/testdb";

        String username = "root";

        String password = "password";

 

        try {

            Connection connection =

                    DriverManager.getConnection(url, username, password);

 

            Statement statement = connection.createStatement();

 

            ResultSet resultSet =

                    statement.executeQuery("SELECT * FROM users");

 

            while (resultSet.next()) {

                System.out.println(

                    resultSet.getString("username")

                );

            }

 

            resultSet.close();

            statement.close();

            connection.close();

 

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}


19. Database Connectivity with Selenium

Selenium and JDBC can be combined to validate complete application workflows.

TestNG

  |

  +---- Selenium WebDriver

  |         |

  |         v

  |    Web Application

  |

  +---- JDBC

            |

            v

        Database

 

Both results

      |

      v

TestNG Assertion


20. Selenium UI Validation with Database Validation

Suppose a registration form creates a new user. Selenium can fill the form and submit it. JDBC can then query the database to verify that the user was actually stored.

Selenium

   |

   v

Fill Registration Form

   |

   v

Click Register

   |

   v

Application Saves User

   |

   v

JDBC Query

   |

   v

Database

   |

   v

Verify User Record


21. Database Validation Example

String expectedUsername = "john123";

 

driver.findElement(By.id("username"))

        .sendKeys(expectedUsername);

 

driver.findElement(By.id("registerButton"))

        .click();

 

String query =

        "SELECT username FROM users WHERE username = ?";

 

PreparedStatement statement =

        connection.prepareStatement(query);

 

statement.setString(1, expectedUsername);

 

ResultSet resultSet =

        statement.executeQuery();

 

if (resultSet.next()) {

    System.out.println("User exists in database");

}


22. Using PreparedStatement

PreparedStatement is used for parameterized SQL queries. It is generally preferred when query values come from test data or application input.

String query =

        "SELECT * FROM users WHERE username = ?";

 

PreparedStatement statement =

        connection.prepareStatement(query);

 

statement.setString(1, "john123");

 

ResultSet resultSet =

        statement.executeQuery();


23. Advantages of PreparedStatement

  • Supports parameterized queries.
  • Separates SQL structure from input values.
  • Helps reduce SQL injection risks.
  • Improves readability for dynamic queries.
  • Can be reused for multiple parameter values.
  • Works well with automation test data.


24. PreparedStatement with Multiple Parameters

String query =

        "SELECT * FROM users WHERE username = ? AND status = ?";

 

PreparedStatement statement =

        connection.prepareStatement(query);

 

statement.setString(1, "john123");

statement.setString(2, "ACTIVE");

 

ResultSet resultSet =

        statement.executeQuery();


25. INSERT Operation

Database connectivity can also be used to insert test data.

String query =

        "INSERT INTO users (username, email) VALUES (?, ?)";

 

PreparedStatement statement =

        connection.prepareStatement(query);

 

statement.setString(1, "john123");

statement.setString(2, "[email protected]");

 

int rows =

        statement.executeUpdate();

 

System.out.println("Rows inserted: " + rows);


26. UPDATE Operation

String query =

        "UPDATE users SET status = ? WHERE username = ?";

 

PreparedStatement statement =

        connection.prepareStatement(query);

 

statement.setString(1, "ACTIVE");

statement.setString(2, "john123");

 

int rows =

        statement.executeUpdate();

 

System.out.println("Rows updated: " + rows);


27. DELETE Operation

String query =

        "DELETE FROM users WHERE username = ?";

 

PreparedStatement statement =

        connection.prepareStatement(query);

 

statement.setString(1, "john123");

 

int rows =

        statement.executeUpdate();

 

System.out.println("Rows deleted: " + rows);


28. executeQuery() vs executeUpdate()

MethodTypical UsageReturn Type
executeQuery()SELECTResultSet
executeUpdate()INSERT, UPDATE, DELETEint
execute()General SQL executionboolean


29. Database Connectivity with TestNG

TestNG can be used to organize database validation tests and perform assertions on the retrieved database values.

import org.testng.Assert;

import org.testng.annotations.Test;

 

@Test

public void databaseValidationTest() {

 

    String expectedUsername = "john123";

 

    String actualUsername = "john123";

 

    Assert.assertEquals(

        actualUsername,

        expectedUsername

    );

}


30. Database Validation Using Assertions

String expectedStatus = "ACTIVE";

String actualStatus = resultSet.getString("status");

 

Assert.assertEquals(

    actualStatus,

    expectedStatus,

    "Database status does not match"

);

Assertions convert database verification into a formal test result.


31. Database Utility Class

In a reusable automation framework, database connection logic should generally be placed in a utility class rather than duplicated across every test.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

 

public class DatabaseUtils {

 

    private static final String URL =

            "jdbc:mysql://localhost:3306/testdb";

 

    private static final String USERNAME = "root";

    private static final String PASSWORD = "password";

 

    public static Connection getConnection()

            throws SQLException {

 

        return DriverManager.getConnection(

            URL,

            USERNAME,

            PASSWORD

        );

    }

}


32. Using Database Utility in a Test

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.PreparedStatement;

 

public class UserDatabaseTest {

 

    public void verifyUser() throws Exception {

 

        Connection connection =

                DatabaseUtils.getConnection();

 

        String query =

                "SELECT username FROM users WHERE username = ?";

 

        PreparedStatement statement =

                connection.prepareStatement(query);

 

        statement.setString(1, "john123");

 

        ResultSet resultSet =

                statement.executeQuery();

 

        if (resultSet.next()) {

            System.out.println(

                resultSet.getString("username")

            );

        }

 

        resultSet.close();

        statement.close();

        connection.close();

    }

}


33. Database Utility with try-with-resources

Java's try-with-resources statement is a useful way to automatically close JDBC resources.

String query =

        "SELECT username FROM users WHERE username = ?";

 

try (Connection connection =

         DatabaseUtils.getConnection();

     PreparedStatement statement =

         connection.prepareStatement(query)) {

 

    statement.setString(1, "john123");

 

    try (ResultSet resultSet =

             statement.executeQuery()) {

 

        while (resultSet.next()) {

            System.out.println(

                resultSet.getString("username")

            );

        }

    }

}


34. Why Resource Management is Important

Database connections, statements, and result sets consume resources. If they are not closed properly, long-running automation suites may experience connection leaks or resource exhaustion.

  • Close ResultSet objects.
  • Close Statement or PreparedStatement objects.
  • Close database connections.
  • Prefer try-with-resources where appropriate.
  • Avoid opening unnecessary connections repeatedly.


35. Database Configuration

Database configuration should ideally be separated from test logic.

db.url=jdbc:mysql://localhost:3306/testdb

db.username=test_user

db.password=test_password

A configuration reader can load these values at runtime.


36. Database Connectivity Using Properties File

Properties properties = new Properties();

 

FileInputStream input =

        new FileInputStream("config.properties");

 

properties.load(input);

 

String url =

        properties.getProperty("db.url");

 

String username =

        properties.getProperty("db.username");

 

String password =

        properties.getProperty("db.password");

 

Connection connection =

        DriverManager.getConnection(

            url,

            username,

            password

        );


37. Never Hard-Code Sensitive Credentials

Database usernames and passwords should not normally be committed as plain text into source control, especially when they provide access to shared environments.

Depending on the project, credentials can be supplied through environment variables, CI/CD secret stores, secure configuration systems, or other approved secret-management solutions.


38. Database Connectivity with Maven

Maven can manage JDBC driver dependencies for the automation project.

For example, a MySQL-based project can include the appropriate MySQL Connector/J dependency in pom.xml.

<dependency>

    <groupId>com.mysql</groupId>

    <artifactId>mysql-connector-j</artifactId>

    <version>YOUR_VERSION</version>

</dependency>

The exact driver version should be selected according to the project's Java version, database version, and dependency-management requirements.


39. Database Connectivity with Data Providers

JDBC and TestNG Data Providers can be combined to create database-driven testing. A Data Provider can retrieve rows from a database and pass them to a test method.

@DataProvider(name = "users")

public Object[][] users() {

 

    // Database query can be executed here.

 

    return new Object[][] {

        {"john123", "ACTIVE"},

        {"david123", "ACTIVE"},

        {"robert123", "INACTIVE"}

    };

}

 

@Test(dataProvider = "users")

public void userTest(

        String username,

        String status) {

 

    System.out.println(username);

    System.out.println(status);

}


40. Database-Driven Test Execution Flow

Database

    |

    v

SQL Query

    |

    v

JDBC

    |

    v

Data Provider

    |

    v

TestNG

    |

    v

Selenium WebDriver

    |

    v

Web Application

    |

    v

Validation


41. Database Connectivity for Login Testing

A database can contain user credentials or user status information required for login testing. The framework can retrieve appropriate test records and use them during UI automation.

Database

    |

    v

Username / User Status

    |

    v

Data Provider

    |

    v

Login Test

    |

    v

Selenium

    |

    v

Login Page

    |

    v

Assertion

Sensitive passwords should be handled through appropriate secure mechanisms rather than exposing them unnecessarily in logs or reports.


42. Database Validation for Registration

Registration testing is a common database validation scenario.

Enter Registration Data

          |

          v

Click Register

          |

          v

Application

          |

          v

Database INSERT

          |

          v

JDBC SELECT

          |

          v

Verify Record

          |

          v

TestNG Assertion


43. Database Validation for E-Commerce Testing

E-commerce applications often require database validation for products, customers, orders, payments, inventory, and shipping information.

UI ActionPossible Database Validation
Add Product to CartCart record
Place OrderOrder record
Apply DiscountDiscount/order amount
Complete PaymentPayment status
Cancel OrderOrder status
Update QuantityInventory/cart quantity


44. Database Connectivity for Search Testing

Database data can also be used to generate search test cases.

Database

    |

    v

Product Names

    |

    v

Data Provider

    |

    v

Selenium Search Test

    |

    v

Search Results

    |

    v

Database / UI Validation


45. Database Connectivity for API and UI Testing

Database validation can be used with both API and UI automation.

API Test

   |

   v

Application Backend

   |

   v

Database

   |

   v

JDBC Validation

 

UI Test

   |

   v

Web Application

   |

   v

Database

   |

   v

JDBC Validation


46. Database Connectivity with Page Object Model

Database utilities should generally remain separate from Page Object classes. Page Objects should focus on UI interactions, while database utilities should handle database operations.

Test Class

    |

    +---- Page Object

    |       |

    |       v

    |   UI Interaction

    |

    +---- Database Utility

            |

            v

        JDBC Query

            |

            v

         Database


47. Recommended Framework Separation

src

|-- test

|   |-- java

|       |-- tests

|       |   |-- LoginTest.java

|       |   |-- RegistrationTest.java

|       |   |-- OrderTest.java

|       |

|       |-- pages

|       |   |-- LoginPage.java

|       |   |-- RegistrationPage.java

|       |   |-- OrderPage.java

|       |

|       |-- database

|       |   |-- DatabaseUtils.java

|       |   |-- DatabaseQueries.java

|       |

|       |-- data

|       |   |-- TestDataProvider.java

|       |

|       |-- utilities

|           |-- ConfigReader.java

|           |-- DriverFactory.java


48. Database Query Utility

Frequently used SQL queries can be maintained in a dedicated utility class.

public class DatabaseQueries {

 

    public static final String GET_USER =

        "SELECT * FROM users WHERE username = ?";

 

    public static final String GET_ORDER =

        "SELECT * FROM orders WHERE order_id = ?";

 

    public static final String GET_PRODUCT =

        "SELECT * FROM products WHERE product_id = ?";

}


49. Database Connectivity with TestNG @BeforeMethod

A database connection can be initialized before a group of tests when the test design requires a shared or controlled connection.

@BeforeMethod

public void setupDatabase() throws Exception {

    connection = DatabaseUtils.getConnection();

}

 

@AfterMethod

public void closeDatabase() throws Exception {

    if (connection != null) {

        connection.close();

    }

}

For parallel execution, shared connections should be avoided unless the design is explicitly thread-safe.


50. Database Connectivity with @BeforeClass

A connection can also be initialized at class level when appropriate.

@BeforeClass

public void setupDatabase() throws Exception {

    connection = DatabaseUtils.getConnection();

}

 

@AfterClass

public void closeDatabase() throws Exception {

    if (connection != null) {

        connection.close();

    }

}


51. Database Connectivity and Parallel Testing

Parallel Selenium tests require careful database design as well. Tests should avoid unintended conflicts when multiple threads access or modify the same database records.

Thread 1

   |

   +---- WebDriver 1

   |

   +---- Database Data 1

 

Thread 2

   |

   +---- WebDriver 2

   |

   +---- Database Data 2

 

Thread 3

   |

   +---- WebDriver 3

   |

   +---- Database Data 3

Test data should be isolated where necessary to prevent one test from changing the data required by another test.


52. Database Transactions

A database transaction is a logical unit of database work. Transactions can be useful when test setup requires multiple related database operations.

connection.setAutoCommit(false);

 

try {

    // INSERT

    // UPDATE

    // Additional database operations

 

    connection.commit();

 

} catch (Exception e) {

 

    connection.rollback();

    throw e;

}


53. Commit and Rollback

OperationPurpose
commit()Permanently applies transaction changes
rollback()Reverts uncommitted transaction changes
setAutoCommit(false)Allows explicit transaction control


54. Database Test Data Setup

Database connectivity can be used to prepare test data before a test begins.

@BeforeMethod

public void createTestData() throws Exception {

 

    String query =

        "INSERT INTO users (username, status) VALUES (?, ?)";

 

    try (PreparedStatement statement =

             connection.prepareStatement(query)) {

 

        statement.setString(1, "testuser");

        statement.setString(2, "ACTIVE");

 

        statement.executeUpdate();

    }

}


55. Database Test Data Cleanup

After a test completes, test-created records can sometimes be removed to keep the environment clean.

@AfterMethod

public void cleanupTestData() throws Exception {

 

    String query =

        "DELETE FROM users WHERE username = ?";

 

    try (PreparedStatement statement =

             connection.prepareStatement(query)) {

 

        statement.setString(1, "testuser");

        statement.executeUpdate();

    }

}

Cleanup should be designed carefully so that it does not delete data belonging to other tests or users.


56. Database Connectivity Error Handling

Database operations can fail because of incorrect credentials, network problems, unavailable servers, invalid SQL, timeouts, or database constraints.

try {

    Connection connection =

        DatabaseUtils.getConnection();

 

} catch (SQLException e) {

    System.out.println(

        "Database connection failed"

    );

    e.printStackTrace();

}


57. Common Database Exceptions

ProblemPossible Cause
SQLExceptionGeneral database operation failure
Connection failureIncorrect URL, server, network, or credentials
SQL syntax errorInvalid SQL statement
Authentication errorInvalid database username/password
TimeoutDatabase server or network response delay
Constraint violationInvalid INSERT or UPDATE operation


58. Common Mistakes in Database Connectivity

  • Using an incorrect JDBC URL.
  • Using the wrong database port.
  • Using incorrect database credentials.
  • Forgetting the JDBC driver dependency.
  • Not closing database resources.
  • Using Statement when parameterized queries are more appropriate.
  • Hard-coding sensitive credentials.
  • Writing database logic directly inside every test class.
  • Sharing database state between parallel tests without isolation.
  • Not handling SQLException properly.
  • Using production databases for destructive test operations.
  • Not cleaning up test data.
  • Writing fragile SQL queries.
  • Not validating the correct database environment.


59. Best Practices for Database Connectivity

  • Keep database logic inside reusable utility classes.
  • Use PreparedStatement for dynamic query values.
  • Use try-with-resources where practical.
  • Keep credentials outside source-controlled code.
  • Use separate test databases or controlled test environments.
  • Use meaningful database query methods.
  • Keep UI logic and database logic separate.
  • Clean up test data when appropriate.
  • Use isolated data for parallel tests.
  • Log useful database information without exposing sensitive data.
  • Validate that the test is connected to the intended environment.
  • Use assertions to convert database checks into test results.


60. Database Connectivity vs Selenium

FeatureSeleniumJDBC
Main PurposeWeb browser automationDatabase connectivity
Works WithWeb application UIDatabase
Typical OperationsClick, type, select, navigateSELECT, INSERT, UPDATE, DELETE
ValidationUI behaviorBackend data
Common APIWebDriverJDBC


61. Database Connectivity vs Data Provider

Data ProviderDatabase Connectivity
Supplies data to testsCommunicates with database
Uses TestNG @DataProviderUses JDBC or database libraries
Can use data from many sourcesSpecifically interacts with database systems
Useful for repeated test executionUseful for database read/write/validation


62. Database Connectivity in a Complete Automation Framework

                 TestNG

                   |

       +-----------+-----------+

       |                       |

       v                       v

 Data Provider             Test Class

       |                       |

       v                       v

 Test Data                Page Objects

                               |

                               v

                        Selenium WebDriver

                               |

                               v

                        Web Application

                               |

                               v

                           Database

                               ^

                               |

                         JDBC Utility

                               |

                               v

                         SQL Queries

                               |

                               v

                           Assertions


63. Complete Practical Database Validation Example

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class RegistrationDatabaseTest {

 

    WebDriver driver;

    Connection connection;

 

    @BeforeMethod

    public void setup() throws Exception {

 

        driver = new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

 

        driver.get("https://example.com/register");

 

        connection =

                DatabaseUtils.getConnection();

    }

 

    @Test

    public void verifyRegistrationInDatabase()

            throws Exception {

 

        String username = "testuser123";

        String email = "[email protected]";

 

        driver.findElement(By.id("username"))

                .sendKeys(username);

 

        driver.findElement(By.id("email"))

                .sendKeys(email);

 

        driver.findElement(By.id("registerButton"))

                .click();

 

        String query =

            "SELECT username, email " +

            "FROM users WHERE username = ?";

 

        try (PreparedStatement statement =

                 connection.prepareStatement(query)) {

 

            statement.setString(1, username);

 

            try (ResultSet resultSet =

                     statement.executeQuery()) {

 

                Assert.assertTrue(

                    resultSet.next(),

                    "User record was not found"

                );

 

                Assert.assertEquals(

                    resultSet.getString("username"),

                    username

                );

 

                Assert.assertEquals(

                    resultSet.getString("email"),

                    email

                );

            }

        }

    }

 

    @AfterMethod

    public void tearDown() throws Exception {

 

        if (connection != null) {

            connection.close();

        }

 

        if (driver != null) {

            driver.quit();

        }

    }

}


64. Real-World Database Testing Example

Consider an e-commerce application where a user places an order.

Step 1:

Login through Selenium

        |

        v

Step 2:

Search Product

        |

        v

Step 3:

Add Product to Cart

        |

        v

Step 4:

Checkout

        |

        v

Step 5:

Place Order

        |

        v

Step 6:

Capture Order ID

        |

        v

Step 7:

JDBC Query

        |

        v

SELECT order_id, status

FROM orders

WHERE order_id = ?

        |

        v

Step 8:

Validate Database Record

        |

        v

Step 9:

TestNG Assertion


65. Database Connectivity for Order Validation

String query =

    "SELECT status FROM orders WHERE order_id = ?";

 

PreparedStatement statement =

    connection.prepareStatement(query);

 

statement.setString(1, orderId);

 

ResultSet resultSet =

    statement.executeQuery();

 

Assert.assertTrue(resultSet.next());

 

String status =

    resultSet.getString("status");

 

Assert.assertEquals(

    status,

    "CONFIRMED"

);


66. Database Connectivity for Backend Validation

Database validation is useful when the UI only displays a limited amount of information. The test can verify backend fields that may not be directly visible in the UI.

Application LayerValidation
UIVisible application behavior
APIService response
DatabasePersisted backend data


67. Database Connectivity and Regression Testing

Database validation can strengthen regression testing by verifying that previously working database operations continue to work after application changes.

  • User creation regression.
  • Login status validation.
  • Product inventory validation.
  • Order creation validation.
  • Payment status validation.
  • Profile update validation.
  • Data deletion validation.


68. Database Connectivity and CI/CD

Database-enabled Selenium tests can run inside CI/CD pipelines when the pipeline has access to the appropriate test environment and database.

Developer Commit

      |

      v

Git Repository

      |

      v

CI/CD Pipeline

      |

      v

Maven Build

      |

      v

TestNG

      |

      +---- Selenium

      |

      +---- JDBC

              |

              v

          Test Database

              |

              v

         Test Results

              |

              v

            Report


69. Database Connectivity and Reporting

Database validation failures should be visible in the automation report. Test reports can identify whether a failure occurred during UI interaction, SQL execution, or database validation.

Test Case

   |

   +---- UI Step

   |

   +---- Database Query

   |

   +---- Database Result

   |

   +---- Assertion

   |

   v

PASS / FAIL

   |

   v

Test Report


70. Practical Project Structure

selenium-automation-framework

|

|-- pom.xml

|

|-- src

|   |-- test

|       |-- java

|           |-- tests

|           |   |-- LoginTest.java

|           |   |-- RegistrationTest.java

|           |   |-- OrderTest.java

|           |

|           |-- pages

|           |   |-- LoginPage.java

|           |   |-- RegistrationPage.java

|           |   |-- OrderPage.java

|           |

|           |-- database

|           |   |-- DatabaseUtils.java

|           |   |-- DatabaseQueries.java

|           |

|           |-- data

|           |   |-- TestDataProvider.java

|           |

|           |-- utilities

|               |-- ConfigReader.java

|               |-- DriverFactory.java

|

|-- src

    |-- test

        |-- resources

            |-- config.properties


71. Database Connectivity Checklist

  • JDBC driver is available.
  • Database URL is correct.
  • Database server is reachable.
  • Database credentials are valid.
  • Required tables exist.
  • SQL queries are valid.
  • PreparedStatement is used for dynamic values.
  • ResultSet is processed correctly.
  • Database resources are closed.
  • Assertions validate expected values.
  • Test data is isolated when required.
  • Sensitive information is not exposed in reports.


72. Interview Questions on Database Connectivity

1. What is JDBC?

JDBC stands for Java Database Connectivity and provides Java APIs for communicating with relational databases.

2. Why is JDBC used in Selenium automation?

JDBC can be used to retrieve test data and validate backend database records during Selenium automation.

3. Does Selenium directly connect to a database?

No. Selenium WebDriver handles browser automation. Database communication is normally implemented separately using JDBC or another database library.

4. What is a JDBC driver?

A JDBC driver is software that enables Java applications to communicate with a specific database.

5. How do you create a database connection?

A connection can commonly be created using DriverManager.getConnection() with the database URL, username, and password.

6. What is ResultSet?

ResultSet represents the rows returned by a SELECT query.

7. What is PreparedStatement?

PreparedStatement represents a parameterized SQL statement and is commonly used when query values are supplied dynamically.

8. What is the difference between Statement and PreparedStatement?

Statement executes SQL directly, while PreparedStatement supports parameterized SQL and is generally preferred for dynamic input values.

9. What is executeQuery()?

executeQuery() is commonly used for SELECT statements and returns a ResultSet.

10. What is executeUpdate()?

executeUpdate() is commonly used for INSERT, UPDATE, and DELETE operations and returns the number of affected rows.

11. Why should database connections be closed?

Connections consume database and application resources. Closing them helps prevent connection leaks and resource exhaustion.

12. How can Selenium validate database data?

Selenium can perform a UI action, JDBC can retrieve the corresponding backend record, and TestNG assertions can compare actual and expected values.

13. Can database data be used with DataProvider?

Yes. A Data Provider can retrieve records from a database and supply them to TestNG test methods.

14. Can database connectivity be used with POM?

Yes. Database utilities and Page Objects can be maintained separately while the test class coordinates both.

15. What is database-driven testing?

Database-driven testing is an approach where test data is retrieved dynamically from a database and supplied to test cases.

16. How can database credentials be protected?

Credentials should be stored using secure configuration, environment variables, CI/CD secrets, or an approved secret-management solution instead of plain-text source-controlled files.

17. What is a transaction?

A transaction is a logical unit of database operations that can be committed or rolled back as a group.

18. What is rollback?

Rollback reverses uncommitted database changes in a transaction.

19. What happens if multiple tests modify the same database record?

Tests can interfere with each other. Test data isolation and controlled test design are important, especially during parallel execution.

20. What are common database testing mistakes?

Common mistakes include incorrect connection configuration, invalid SQL, unclosed resources, hard-coded credentials, unsafe shared data, and insufficient cleanup.


73. Quick Reference Table

ConceptDescription
JDBCJava API for database connectivity
DriverManagerUsed to obtain database connections
ConnectionRepresents a database connection
StatementExecutes SQL statements
PreparedStatementExecutes parameterized SQL statements
ResultSetContains data returned by SELECT queries
executeQuery()Commonly executes SELECT queries
executeUpdate()Commonly executes INSERT, UPDATE, DELETE
commit()Commits a transaction
rollback()Rolls back uncommitted transaction changes
SeleniumAutomates the web UI
TestNGManages tests and assertions


74. Learning Roadmap for Database Connectivity

  1. Understand relational database fundamentals.
  2. Learn basic SQL commands.
  3. Understand JDBC architecture.
  4. Learn JDBC drivers.
  5. Create a basic database connection.
  6. Execute SELECT queries.
  7. Read ResultSet values.
  8. Learn PreparedStatement.
  9. Perform INSERT, UPDATE, and DELETE operations.
  10. Learn database transactions.
  11. Create a reusable Database Utility.
  12. Connect database utilities with TestNG.
  13. Use database data with Data Providers.
  14. Combine JDBC with Selenium.
  15. Implement UI-to-database validation.
  16. Integrate database testing with Page Object Model.
  17. Manage test data and cleanup.
  18. Implement thread-safe database access for parallel tests.
  19. Integrate database-enabled tests with Maven and CI/CD.
  20. Build a complete end-to-end Selenium automation framework.


75. Practical Exercises

  1. Create a JDBC connection to a test database.
  2. Retrieve all users from a users table.
  3. Search for a specific user using PreparedStatement.
  4. Insert a new test user into the database.
  5. Update the status of a test user.
  6. Delete a test record after execution.
  7. Create a reusable DatabaseUtils class.
  8. Create a TestNG database validation test.
  9. Use database data in a TestNG Data Provider.
  10. Automate a registration form using Selenium and validate the new record in the database.
  11. Automate an order workflow and verify the order status in the database.
  12. Combine Selenium, POM, TestNG, JDBC, Maven, and reporting in one project.


76. Real-World End-to-End Example

Suppose a customer registers on an e-commerce application.

1. Launch Browser

        |

        v

2. Open Registration Page

        |

        v

3. Enter Customer Details

        |

        v

4. Submit Registration

        |

        v

5. Application Processes Request

        |

        v

6. Database INSERT

        |

        v

7. Capture Customer ID

        |

        v

8. Execute JDBC SELECT

        |

        v

9. Retrieve Customer Record

        |

        v

10. Compare Expected vs Actual

        |

        v

11. TestNG Assertion

        |

        v

12. Generate Test Report


77. Complete Automation Architecture

                    TestNG

                       |

          +------------+------------+

          |                         |

          v                         v

    Test Classes               Data Providers

          |                         |

          v                         v

    Page Objects              Test Data

          |

          v

   Selenium WebDriver

          |

          v

    Web Application

          |

          v

       Backend

          |

          v

      Database

          ^

          |

     JDBC Utility

          |

          v

     SQL Queries

          |

          v

     DB Validation

          |

          v

      Assertions

          |

          v

      Reporting


78. Advantages of Database Connectivity

  • Backend Validation: Verifies that UI operations correctly affect database records.
  • Dynamic Test Data: Test data can be retrieved dynamically.
  • End-to-End Testing: UI and backend behavior can be validated together.
  • Data-Driven Testing: Database records can be supplied to test methods.
  • Reusable Utilities: Database operations can be centralized in utility classes.
  • Improved Coverage: More backend scenarios can be validated.
  • Integration Testing: Helps validate application-to-database integration.


79. Limitations of Database Connectivity

  • Requires database access and suitable permissions.
  • Database configuration can differ between environments.
  • Incorrect test data cleanup can affect subsequent tests.
  • Database-dependent tests may be slower than isolated UI tests.
  • Parallel tests require careful data isolation.
  • SQL knowledge is required.
  • Database schema changes can affect automation tests.
  • Credentials and database access must be managed securely.


80. Summary

Database Connectivity is an important capability in advanced Selenium automation frameworks. Selenium WebDriver handles browser automation, while JDBC provides a mechanism for Java-based test frameworks to communicate with relational databases.

Database connectivity can be used to retrieve test data, create test data, update records, clean up test data, and validate backend information after UI actions.

A typical implementation uses Connection, PreparedStatement, ResultSet, SQL queries, TestNG assertions, and reusable database utility classes.

For enterprise-level automation frameworks, database connectivity can be combined with Selenium WebDriver, TestNG, Data Providers, Page Object Model, Maven, CI/CD, parallel execution, and reporting to create comprehensive end-to-end automation solutions.


81. Course Resources

Learn more about Selenium automation testing and related framework concepts:

Final Takeaway: Database Connectivity allows Selenium automation frameworks to go beyond UI validation by interacting with backend database systems. When JDBC, Selenium, TestNG, Data Providers, POM, and SQL are combined correctly, automation tests can validate complete application workflows from the user interface through the backend database.

whatsapp