Database connection in Java

In the previous post, we have learnt about Collection Framework. In this post, we will see how to connect to the database in java.

There are following steps which we need to follow to connect to a database.

  • Register the Driver Class
  • Create the connection
  • Create the statement Object
  • Execute the queries
  • Close Database connection

Let’s understand all these steps one by one.

1) Register the Driver Class:

The forName() method of Class ‘class’ is used to register the driver class. It loads the driver class dynamically.


public static void forName(String className)throws ClassNotFoundException

Example to register the Oracle driver class:


2) Create the Connection Object:

The getConnection() method of DriverManager class is used to establish connection with the database.


There are 2 ways.

public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException


Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@<localhost>:<port no>:<DB name>”,”user”,”password”);

3) Create the statement Object:

The createStatement() method of Connection interface is used to create statement. The object of statement is used to execute queries with the database connection.


public Statement createStatement()throws SQLException


Statement stmt=con.createStatement();

4) Execute the query:

The method executeQuery() od statement interface is used to execute the query with the database.This method returns the object of ResultSet that can be used to get all the records of a table.


public ResultSet executeQuery(String sql)throws SQLException


After getting the resultset object, we can create a while loop where we can fetch the record with the method next(). Column values can be fetched by using methods getInt , getString depending on the data type .

ResultSet rs=stmt.executeQuery("select * from emp");  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  

5) Close Database connection:

By closing connection, statement and resultSet objects will be closed automatically. We use the method close() of connection interface.


public void close()throws SQLException



Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...