Steps to connect Database using JAVA

JDBC is JAVA API for Database Connectivity. It is very useful API that facilitates database connectivity directly from JAVA application.

Follow these steps to connect database from JAVA. You can connect to any database but for this tutorial, I will show you connecting MySQL database. To connect any other database, you just need to change database specific driver in step 1.


Step 1: Load JDBC driver for mysql database

Load JDBC driver using Class.forName(). Driver specifc to MySQL database is : com.mysql.jdbc.Driver

	
    //load jdbc driver for mysql database
    try {
	Class.forName("com.mysql.jdbc.Driver");
    }catch(Exception e) {
	System.out.println("Unable to load Driver");
    }

 

Step 2: Establish connection using DriverManager

Establish connection using getConnection method of static class DriverManager. This method takes 3 arguments. First one is the URL of database, second parameter is the username of the database and third parameter is the password for that user. 

	
  try {
      Connection connection = 
       DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "root", "root");
  } catch (SQLException e) {
       System.out.println("Unable to connect to database");
  }

 

Step 3: Create statement object

If connection is successfully established, create statement object using createStatement() method of connection object. 

       
   if(connection != null) {
        try {
	     Statement statement = connection.createStatement();
	} catch (SQLException e) {
	     System.out.println("Unable to create statement");
	}
   }

Step 4: Execute or update query

If statement is successfully created, execute the query using  executeQuery () method of statement object. It takes SQL statement as parameter. 

executeQuery() method returns the ResultSet object that will return the results to JAVA application.

 

 
    if(statement != null) {
	try {
	     ResultSet resultSet = statement.executeQuery("SELECT * FROM orders");
	} catch (SQLException e) {
	     System.out.println("Unable to create statement");
	}
    }

 

Step 5: Iterate over ResultSet object

Once ResultSet object is received and if it is not null and not empty, you can iterate over that object and get the results.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Example {
	
      public void connectToDatabase(){
		
	//declare connection, statement and resutset objects 
        Connection connection = null;
	Statement statement = null;
	ResultSet resultSet = null;
	
	//load jdbc driver for mysql database
	try {
		Class.forName("com.mysql.jdbc.Driver");
	}catch(Exception e) {
		System.out.println("Unable to load Driver");
	}
	
	//Establish connection using DriverManager 
	try {
	 connection = 
        DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "root", "root");
	} catch (SQLException e) {
		System.out.println("Unable to connect to database");
	}
		
	//if connection is successfully established, create statement
        if(connection != null) {
	    try {
	       statement = connection.createStatement();
	    } catch (SQLException e) {
	       System.out.println("Unable to create statement");
	    }
	}
		
	//if statement is created successfully, execute query and get results
        if(statement != null) {
	   try {
	        resultSet = statement.executeQuery("SELECT * FROM orders");
	   } catch (SQLException e) {
	        System.out.println("Unable to create statement");
	   }
        }
		
	//if resultset is received and is not empty,
   	// iterate over resultset to get values
        if(resultSet != null) {
	   try {
		while(resultSet.next()) {
		   System.out.println("Value in 1st column "+resultSet.getString(1));
		}
	   } catch (SQLException e) {
	        System.out.println("Unable to iterate over resultset");
	   }
	}
		
	try {
	     resultSet.close();
	     statement.close();
	     connection.close();
	} catch (SQLException e) {
	     e.printStackTrace();
	}
     }
	
     public static void main(String[] args) {
	Example example = new Example();
	example.connectToDatabase();
     }
}
comments powered by Disqus