How to connect Database using JDBC

How to connect Database using JDBC?

Table of Contents

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(“com.mysql.jdbc.Driver");
// 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.

con.createStatement();

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
Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training