How to Connect to SQL Database From Selenium?

Check this

import java.sql.*;
import org.openqa.selenium.*;

public class SeleniumDatabaseExample {

    public static void main(String[] args) throws Exception {

        // ✅ Step 1: DB connection
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", "root", "root");

        Statement stmt = con.createStatement();

        // ✅ Step 2: Execute SQL
        ResultSet rs = stmt.executeQuery(
                "SELECT username FROM users WHERE id = 101");

        rs.next();
        String dbUsername = rs.getString("username");

        // ✅ Step 3: Selenium UI validation
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

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

        String uiUsername =
                driver.findElement(By.id("username")).getText();

        System.out.println("DB Username: " + dbUsername);
        System.out.println("UI Username: " + uiUsername);

        // ✅ Step 4: Compare
        if (uiUsername.equals(dbUsername)) {
            System.out.println("✅ Data matched");
        } else {
            System.out.println("❌ Data mismatch");
        }

        // ✅ Cleanup
        driver.quit();
        con.close();
    }
}

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment