---
description: Selenium Webdriver is limited to testing your applications using Browser. To use Selenium Webdriver for Database Testing you need to use the JDBC (&quot;Java Database Connectivity&quot;).
title: "Database Testing Using Selenium and JDBC: How to Connect?"
image: https://www.guru99.com/images/database-testing-using-selenium-1.png
---

[Skip to content](#main)

**⚡ Smart Summary**

Database testing using Selenium relies on JDBC, because WebDriver itself validates only the browser layer. These steps show how to open a MySQL connection, run SQL, read a ResultSet, and verify stored data.

- 🔌 **JDBC bridge:** Selenium WebDriver drives the browser only, so JDBC supplies the database layer for every data assertion.
- 🧩 **Driver class:** Modern MySQL Connector/J registers com.mysql.cj.jdbc.Driver automatically, so an explicit Class.forName call is optional.
- 🔗 **Connection string:** A MySQL URL follows jdbc:mysql://host:3306/database, and 3306 is the default server port.
- 📥 **Result handling:** Statement.executeQuery returns a ResultSet, which you iterate with next() and read through getString.
- 🛡️ **Resource safety:** try-with-resources closes Connection, Statement, and ResultSet even when an assertion fails midway.
- 🚀 **Query hygiene:** PreparedStatement parameters remove injection risk and let the server reuse a cached execution plan.

Read More

![Database Testing using Selenium](https://www.guru99.com/images/database-testing-using-selenium-1.png)

## Database Connection in Selenium

Selenium Webdriver is limited to [ Testing](https://www.guru99.com/software-testing.html) your applications using Browser. To use Selenium Webdriver for Database Verification you need to use the JDBC (“Java Database Connectivity”).

JDBC (Java Database Connectivity) is a [ SQL](https://www.guru99.com/sql.html) level API that allows you to execute SQL statements. It is responsible for the connectivity between the [ Java](https://www.guru99.com/java-tutorial.html) Programming language and a wide range of databases. The JDBC API provides the following classes and interfaces

- Driver Manager
- Driver
- Connection
- Statement
- ResultSet
- SQLException

## How to Connect Database in Selenium

In order to test your Database using Selenium, you need to observe the following 3 steps

[![Connect Database in Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes1.png)

## Step 1) Make a connection to the Database

In order to make a connection to the database the syntax is

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

Here,

- Userid is the username configured in the database
- Password of the configured user
- URL is of format jdbc:< dbtype>://ipaddress:portnumber/db\_name”
- \<dbtype>- The driver for the database you are trying to connect. To connect to oracle database this value will be “oracle”. For connecting to database with name “emp” in MYSQL URL will be jdbc:mysql://localhost:3036/emp

And the code to create connection looks like

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

You also need to load the JDBC Driver using the code

```
Class.forName("com.mysql.jdbc.Driver");

```

⚠️ **Warning:** com.mysql.jdbc.Driver was deprecated in Connector/J 8.0. Use com.mysql.cj.jdbc.Driver. Since JDBC 4.0 the driver self-registers, so Class.forName is optional. MySQL listens on 3306, not 3036.

## Step 2) Send Queries to the Database

Once connection is made, you need to execute queries.

You can use the Statement Object to send queries.

```
Statement stmt = con.createStatement();
```

Once the statement object is created use the executeQuery method to execute the SQL queries

```
stmt.executeQuery(select *  from employee;);
```

⚠️ **Warning:** executeQuery takes a String, so quote the SQL: executeQuery(“select \* from employee”). Use PreparedStatement for user input.

## Step 3) Process the results

Results from the executed query are stored in the ResultSet Object.

Java provides loads of advance methods to process the results. Few of the methods are listed below

[![Process The Results]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes2.png)

## Example of Database Testing with Selenium

**Step 1)** Install [MySQL Server](https://dev.mysql.com/downloads/mysql/) and [MySQL Workbench](https://dev.mysql.com/downloads/workbench/)

Check out the complete guide to Mysql & Mysql Workbench [here](https://www.guru99.com/sql.html)

While installing MySQL Server, please note the database

- Username
- Password
- Port Number

It will be required in further steps.

MySQL Workbench makes it easy to administer the database without the need to code SQL. Though, you can also use the MySQL Terminal to interact with the database.

**Step 2)** In MySQL WorkBench, connect to your MySQL Server

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes3.png)

In the next screen,

1. Select Local Instance of MySQL
2. Enter Port Number
3. Enter Username
4. Enter Password
5. Click OK

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes4.png)

**Step 3)** To Create Database,

1. Click create Schema Button
2. Enter Name of Schema/Database
3. Click Apply

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes5.png)

**Don't Miss:**

- [WebElement in Selenium](https://www.guru99.com/accessing-forms-in-webdriver.html)
- [AutoIT in Selenium Tutorial: How to use it?](https://www.guru99.com/use-autoit-selenium.html)
- [How to Execute Failed Test Cases in TestNG](https://www.guru99.com/run-failed-test-cases-in-testng.html)
- [How to Upload & Download a File using Selenium](https://www.guru99.com/upload-download-file-selenium-webdriver.html)

**Step 4)** In the navigator menu,

1. Click on Tables, beneath the emp database
2. Enter Table name as employee
3. Enter Fields as Name and Age
4. Click Apply

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes6.png)

You will see the following pop-up. Click Apply

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes7.png)

**Step 5)** We will create following data

| Name | Age |
| --- | --- |
| Top | 25 |
| Nick | 36 |
| Bill | 47 |

To create data into the Table

1. In navigator, select the employee table
2. In right pane, click Form Editor
3. Enter Name and Age
4. Click Apply

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes8.png)

Repeat the process until all data is created

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes9.png)

**Step 6)** Download the MySQL JDBC connector [here](https://dev.mysql.com/downloads/connector/j/)

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes10.png)

**Step 7)** Add the downloaded Jar to your Project

1. Right click on your Java File. Then click on Build Path à Configure build path
2. Select the libraries
3. Click on add external JARs
4. You can see MySQL connector java in your library
5. Click on open to add it to the project

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes11.png)

**Step 8)** Copy the following code into the editor

```
Package  htmldriver;		
import  java.sql.Connection;		
import  java.sql.Statement;		
import  java.sql.ResultSet;		
import  java.sql.DriverManager;		
import  java.sql.SQLException;		
public class  SQLConnector {				
    	public static void  main(String[] args) throws  ClassNotFoundException, SQLException {													
				//Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name" String dbUrl = "jdbc:mysql://localhost:3036/emp";					

				//Database Username String username = "root";	
                
				//Database Password String password = "guru99";				

				//Query to Execute String query = "select *  from employee;";	
                
         	    //Load mysql jdbc driver Class.forName("com.mysql.jdbc.Driver");			
           
           		//Create Connection to DB Connection con = DriverManager.getConnection(dbUrl,username,password);
          
          		//Create Statement Object Statement stmt = con.createStatement();					
       
       			// Execute the SQL Query. Store results in ResultSet ResultSet rs= stmt.executeQuery(query);							
         
         		// While Loop to iterate through all data and print results while (rs.next()){
			        		String myName = rs.getString(1);								        
                            String myAge = rs.getString(2);					                               
                            System. out.println(myName+"  "+myAge);		
                    }		
      			 // closing DB Connection
      			con.close();			
		}
}

```

⚠️ **Warning:** Listing preserved as published. Modern equivalents: com.mysql.cj.jdbc.Driver, port 3306, lowercase package, and try-with-resources for cleanup.

**Step 9)** Execute the code, and check the output

[![Database Testing With Selenium]()](https://www.guru99.com/images/6-2015/052615_1013_DatabaseTes12.png)

The same steps apply to any relational engine.

## JDBC Drivers and Connection Strings for Popular Databases

MySQL is only one option. The JDBC pattern stays identical across engines: the imports, the Statement call, and the ResultSet loop do not change. Only the driver artifact and the URL differ, so use the table below when the application under test runs on another database.

| Database | Driver class | Sample connection URL | Default port |
| --- | --- | --- | --- |
| MySQL | com.mysql.cj.jdbc.Driver | jdbc:mysql://localhost:3306/emp | 3306 |
| PostgreSQL | org.postgresql.Driver | jdbc:postgresql://localhost:5432/emp | 5432 |
| Oracle | oracle.jdbc.OracleDriver | jdbc:oracle:thin:@localhost:1521:orcl | 1521 |
| SQL Server | com.microsoft.sqlserver.jdbc.SQLServerDriver | jdbc:sqlserver://localhost:1433;databaseName=emp | 1433 |

Port numbers cause most first-time failures. A connection refused error almost always means the port in the URL does not match the port the server actually listens on. Check your server configuration before assuming the default.

Each driver ships as a single JAR that you add to the build path exactly as shown in Step 7. Every engine listed above registers itself automatically, so no Class.forName line is required. That means a single helper method can serve every environment your suite targets.

## FAQs

🔌 Do I need Class.forName to load the MySQL JDBC driver?

No. Since JDBC 4.0 (Java 6), DriverManager discovers drivers through the ServiceLoader mechanism, so adding the Connector/J JAR to the classpath is enough. Keep the call only when a legacy container fails to register the driver automatically.

⚠️ Why does Selenium report “No suitable driver found” for jdbc:mysql?

The Connector/J JAR is missing from the runtime classpath, or the URL is malformed. Confirm the JAR appears under Referenced Libraries, and check that the URL begins with jdbc:mysql:// and names a reachable host and port.

🤖 Can AI tools generate JDBC verification code for Selenium suites?

Yes. Assistants such as [GitHub Copilot](https://github.com/features/copilot) scaffold connection helpers, ResultSet loops, and assertions from a schema description. Review every generated query for correct table names and injection safety before committing.

🧠 How does AI help maintain database test data?

AI models generate realistic seed rows, suggest boundary values, and flag assertions that drift after a schema migration. Platforms such as [Testim](https://www.testim.io/) apply this to upkeep, though human review remains necessary for referential integrity.

🛡️ Should database connections be closed inside Selenium tests?

Always. An unclosed Connection or ResultSet exhausts the server connection pool across a long suite. Wrap them in try-with-resources, or close them in an @AfterMethod block so cleanup runs even when an assertion fails.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/database-testing-using-selenium-1.png","url":"https://www.guru99.com/images/database-testing-using-selenium-1.png","width":"700","height":"250","caption":"Database Testing using Selenium","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/selenium","name":"Selenium"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html","name":"Database Testing Using Selenium and JDBC: How to Connect?"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#webpage","url":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html","name":"Database Testing Using Selenium and JDBC: How to Connect?","dateModified":"2026-07-30T20:36:47+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/database-testing-using-selenium-1.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta","url":"https://www.guru99.com/author/admin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","url":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","caption":"Krishna Rungta","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Selenium","headline":"Database Testing Using Selenium and JDBC: How to Connect?","description":"Selenium Webdriver is limited to testing your applications using Browser. To use Selenium Webdriver for Database Testing you need to use the JDBC (&quot;Java Database Connectivity&quot;).","keywords":"selenium","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta"},"dateModified":"2026-07-30T20:36:47+05:30","image":{"@id":"https://www.guru99.com/images/database-testing-using-selenium-1.png"},"copyrightYear":"2026","name":"Database Testing Using Selenium and JDBC: How to Connect?","subjectOf":[{"@type":"HowTo","name":"How to Connect Database in Selenium:","description":"Here is a step-by-step process on How to Connect Database in Selenium:","step":[{"@type":"HowToStep","name":"Step 1) Make a connection to the Database.","text":"DriverManager.getConnection(URL, 'userid', 'password')","url":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#step1"},{"@type":"HowToStep","name":"Step 2) Create Query to the Database using the Statement Object.","text":"Statement stmt = con.createStatement();","url":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#step2"},{"@type":"HowToStep","name":"Step 3) Send the query to database using execute query and store the results.","text":"ResultSet rs = stmt.executeQuery(select * from employee;);","url":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#step3"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Do I need Class.forName to load the MySQL JDBC driver?","acceptedAnswer":{"@type":"Answer","text":"No. Since JDBC 4.0 (Java 6), DriverManager discovers drivers through the ServiceLoader mechanism, so adding the Connector/J JAR to the classpath is enough. Keep the call only when a legacy container fails to register the driver automatically."}},{"@type":"Question","name":"Why does Selenium report \u201cNo suitable driver found\u201d for jdbc:mysql?","acceptedAnswer":{"@type":"Answer","text":"The Connector/J JAR is missing from the runtime classpath, or the URL is malformed. Confirm the JAR appears under Referenced Libraries, and check that the URL begins with jdbc:mysql:// and names a reachable host and port."}},{"@type":"Question","name":"Can AI tools generate JDBC verification code for Selenium suites?","acceptedAnswer":{"@type":"Answer","text":"Yes. Assistants such as GitHub Copilot scaffold connection helpers, ResultSet loops, and assertions from a schema description. Review every generated query for correct table names and injection safety before committing."}},{"@type":"Question","name":"How does AI help maintain database test data?","acceptedAnswer":{"@type":"Answer","text":"AI models generate realistic seed rows, suggest boundary values, and flag assertions that drift after a schema migration. Platforms such as Testim apply this to upkeep, though human review remains necessary for referential integrity."}},{"@type":"Question","name":"Should database connections be closed inside Selenium tests?","acceptedAnswer":{"@type":"Answer","text":"Always. An unclosed Connection or ResultSet exhausts the server connection pool across a long suite. Wrap them in try-with-resources, or close them in an @AfterMethod block so cleanup runs even when an assertion fails."}}]}],"@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#schema-265826","isPartOf":{"@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/database-testing-using-selenium-step-by-step-guide.html#webpage"}}]}
```
