QA Tutorials

How to connect Database using JDBC?

There are steps for connectivity of database. Before proceeding, you need to have MySQL connector. It can be downloaded from Download MySQL connector Jar and add it as a build path by adding Selenium web driver jar.

Below are the steps: 

  1. Load and register the driver
  2. Establish connection
  3. Creating statement object
  4. Execute the statement
  5. Closing the connection
  1. Load and register the driver

For registering the driver we load the driver class using the name forName() method. This method loads the class which is mentioned as parameter.

// class.forName load the Driver class
  1. Establishing the Connection:

For establishing connection with database static method called getConnection () is activated which is present in DriverManagerClass it has three arguments of string type URL, username and password.

DriverManager.getConnection (“jdbc:mysql://localhost:3306 Employee”,"root","root");

URL contains JDBC (main protocol): MySQL (sub protocol for  mySql)://localhost:3306(sub name for mySql(host:prot)/Employee(database) when this method returns an connection object that is

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Employee","root","root"); 
  1. Creating statement object

For creating statement object a method is called createStatement() which is called present connection interface.


which returns the object with no argument like

Statement st= con.createStatement();
  1. Executing Queries

For executing queries there are different methods in statement interface by retrieving records and updating records. For fetching queries we call method like executeQuery (string qry) by taking string as parameter.

st.executeQuery ("Select * from Employee");

This returns the object as resultset object

Resultset rs= st.executeQuery ("Select * from Employee”);

// once executeQuery() executes the query and stores the records in to ResultSet object.

  1. Close connection
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button