Monday 5 December 2016

Steps Required Connecting a Java Application to database:




Step 1 : Register The Driver Class

Step 2 : Create The Connection Object

Step 3 : Create The Statement Object

Step 4 : Execute The Queries

Step 5 : Close The DB Resources



Step 1 : Register The Driver Class

The first step in connecting the database with your java program is registering the driver class of the database. This step need to be performed only once for the whole execution of an application. You can register a driver using class either  Class.forName() method or using DriverManager.registerDriver() method. As both these methods throw checked exceptions, you have to handle them using try-catch blocks.

Below two examples show how to register the driver class of the Oracle database using both these methods. oracle.jdbc.driver.OracleDriver is the driver class of the Oracle database. Remember to update the classpath with JDBC driver of the Oracle database. Otherwise, you will get ClassNotFoundException.

Using Class.forName() Method :

try
{
    Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
    System.out.println("Class Not Found");
}

You can also use Class.forName() method like below. For this, you have add two more catch blocks.

try
{
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch (ClassNotFoundException e)
{
    System.out.println("Driver Class Not Found");
}
catch (InstantiationException e)
{
    System.out.println("Driver Class Can Not Be Instantiated");
}
catch (IllegalAccessException e)
{
    System.out.println("Driver Class Can Not Be Accessed");
}

Using DriverManager.registerDriver() Method :

try
{
    Driver driver = new oracle.jdbc.driver.OracleDriver();

    DriverManager.registerDriver(driver);
}
catch (SQLException e)
{
    System.out.println("Driver Class Can Not Be Loaded");
}

Step 2 : Create The Connection Object

To establish a connection to the data base getConnection method of driverManager class is used. getConnection() method has three overloaded forms. They are,
  • getConnection(String URL, String username, String password) throws SQLException
  • getConnection(String URL) throws SQLException
  • getConnection(String URL, Properties prop) throws SQLException
URL represents an address of the database you want to connect with. The format of this URL changes from one database to another. Below table shows some of the popular databases, their driver class and their URL format.


Below three code snippets shows how to get the Connection object using above three forms of the getConnection() method.

Using getConnection(String URL, String username, String password) :

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

String username = "username";

String password = "password";

Connection con = DriverManager.getConnection(URL, username, password);

Using getConnection(String URL) :

Here, URL consist of URL of the database, username and password.

String URL = "jdbc:oracle:thin:username/password@localhost:1521:XE";

Connection con = DriverManager.getConnection(URL);

Using getConnection(String URL, Properties prop) :

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

Properties prop = new Properties();

prop.put("username", "username");

prop.put("password", "password");

Connection con = DriverManager.getConnection(URL, prop);

Step 3 : Create The Statement Object

 To create the Statement object, we use createStatement() method of Connection object.

Statement stmt = con.createStatement();

Step 4 : Execute The Queries

To send the queries to the database we use executeQuery() method of Statement object. This method returns one java.sql.ResultSet object which contains all the records returned by a query. You can use this ReultSet object to process the records.

String sql = "select * from tableName";

ResultSet rs = stmt.executeQuery(sql);

while(rs.next())
{
    //Process the records here
}

Step 5 : Close The DB Resources

Last but equally important step is closing the DB resources i.e the closing Connection, Statement and ResultSet objects. To close these objects, we use close() method of respective object.

try
{
    if(rs!=null)
    {
        rs.close();
        rs=null;
    }
}
catch (SQLException e)
{
    e.printStackTrace();
}
try
{
    if(stmt!=null)
    {
        stmt.close();
        stmt=null;
    }
}
catch (SQLException e)
{
    e.printStackTrace();
}
try
{
    if(con!=null)
    {
        con.close();
        con=null;
    }
}
catch (SQLException e)
{
    e.printStackTrace();
}

Below example shows how to interact with the ‘Oracle’ database using above 5 steps.

import java.sql.*;

public class MainClass
{
    static
    {
        //STEP 1 : Registering The Driver Class

        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("Unable To Load The class");
        }
    }

    public static void main(String[] args)
    {
        Connection con = null;

        Statement stmt = null;

        ResultSet rs = null;

        try
        {
            String URL = "jdbc:oracle:thin:@localhost:1521:XE";

            String username = "username";

            String password = "password";

            //STEP 2 : Creating The Connection Object

            con = DriverManager.getConnection(URL, username, password);

            //STEP 3 : Creating The Statement Object

            stmt = con.createStatement();

            String sql = "select * from AnyTable";

            //Step 4 : Executing The Queries

            rs = stmt.executeQuery(sql);

            while(rs.next())
            {
                //Process the records here
            }
        }
        catch (SQLException e)
        {
            System.out.println("SQLException Occurred");
        }
        finally
        {
            //STEP 5 : Closing The DB Resources

            try
            {
                if(rs!=null)
                {
                    rs.close();
                    rs=null;
                }
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
            try
            {
                if(stmt!=null)
                {
                    stmt.close();
                    stmt=null;
                }
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
            try
            {
                if(con!=null)
                {
                    con.close();
                    con=null;
                }
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}
 

0 comments:

Post a Comment

Powered by Blogger.

Stats