Connecting Java to a Database


In programs involving working with databases, JDBC (Java Database Connectivity) applications are preferred over others. There are 5 integral steps to connect to a database in Java:

  • Register the Data Class
  • Establish Connection
  • Create Statement
  • Perform Queries
  • Close Connection

Registering the Driver Class

The Driver class is registered using the forName() method of the Class class.
The syntax is as follows: public static void forName (String className) throws ClassNotFoundException

For example: if you have an Oracle driver, to load it, you will have to execute this: Class.forName(“oracle.jdbc.driver.OracleDriver”);

Establishing Connection

A connection is established using the getConnection() method of the DriverManager class.
Syntax: public static Connection getConnection(String url) throws SQLException
public static void Connection getConnection(String url, String name, String password) throws SQLException

For example: To establish connection with the Oracle DB: Connection con=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe”,”system”,”password”);

Creating Statement Object

Method used: createStatement() of the Connection interface.
Syntax: public Statement createStatement() throws SQLException

For example: Statement stmt = con.createStatement();

Performing Queries

Queries are requests that require the program to fetch information from the database.
Syntax: public ResultSet executeQuery (String sql) throws SQLException.

For Example:

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


Closing the Connection Object

The last and final step to establishing a connection is to close the connection object. This means that the entire process has been successfully completed. When you close the connection object, the ResultSet automatically closes. We will use the close() method of the Connection interface.
Syntax: public void close () throws SQLException

For example: con.close();


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


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.