Steps to Connect with Database in JDBC

Steps to Connect a Java Application to Database

There are following five steps to create the database connection with Java application:
1. Register the Driver
2. Create Connection
3. Create SQL Statement
4. Execute SQL Queries
5. Close the Connection

1. Register the driver

The Class.forName() method is used to register the driver class dynamically.

For example:
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");

2. Create the Connection Object

The DriverManager class provides the getConnection() method to establish connection object. It requires to pass a database url, username and password.

Syntax

getConnection(String url);
getConnection(String url, String username, String password);
getConnection(String url, Properties Info);


Example : Creating connection with oracle driver
Connection con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE","username","password");

3. Create SQL Statement

The Connection interface provides the createStatement() method to create SQL statement.

Syntax:
public Statement createStatement( ) throws SQLException

Example:
Statement stmt = con.createStatement();

4. Execute SQL Queries

The Statement interface provides the executeQuery( ) method to execute SQL statements.

Syntax:
public ResultSet executeQuery(String sql) throw SQLException

Example

ResultSet rs = stmt.executeQuery("select * from students");
while (rs.next())
{
     System.out.println (rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3));
}

5. Closing the Connection

The Connection interface provides close( ) method, used to close the connection. It is invoked to release the session after execution of SQL statement.  

Syntax:
public void close( ) throws SQLException

Example:
con.close( );

Note: We will discuss whole program in JDBC using oracle database with type 4 (Thin) driver.

Example : Connect the Java application with Oracle database

import java.sql.*;
class JDBCDemo
{
     public static void main(String args[])
     {
          try
          {
               //Load the driver
               Class.forName("oracle.jdbc.driver.OracleDriver");
    
               //Cretae the connection object
               Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott", "tiger");
    
               //Create the Statement Object
               Statement stmt = con.createStatement();
    
               //Excute the SQL query
               ResultSet rs = stmt.executeQuery("Select * from students");
               while (rs.next())
               {
                    System.out.println (rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3));
               }
               //Closing the connection object
               con.close();
               stmt.close();
               rs.close();
          }
          catch(Exception e)
          {
               System.out.println(e);
          }
     }
}