0% found this document useful (0 votes)
200 views

Java Database Connectivity With 5 Steps

The document discusses the 5 steps to connect a Java application to a database using JDBC: 1) Register the JDBC driver class, 2) Create a connection object, 3) Create a statement object, 4) Execute queries, and 5) Close the connection. It provides code examples for connecting to an Oracle database and retrieving data from a table.

Uploaded by

Ayele Mitku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views

Java Database Connectivity With 5 Steps

The document discusses the 5 steps to connect a Java application to a database using JDBC: 1) Register the JDBC driver class, 2) Create a connection object, 3) Create a statement object, 4) Execute queries, and 5) Close the connection. It provides code examples for connecting to an Oracle database and retrieving data from a table.

Uploaded by

Ayele Mitku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Java Database Connectivity with 5 Steps

There are 5 steps to connect any java application with the database using JDBC.

These steps are as follows:

 Register the Driver class


 Create connection
 Create statement
 Execute queries
 Close connection

1) Register the driver class


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

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundExcepti
on  
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need
to put vender's Jar in the classpath, and then JDBC driver manager can detect
and load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");  

2) Create the connection object


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

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException  
2. 2) public static Connection getConnection(String url,String name,String pass
word)  
3. throws SQLException  

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(  
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");  

3) Create the Statement object


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

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException  

Example to create the statement object

1. Statement stmt=con.createStatement();  
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query

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

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException  

Example to close connection

1. con.close();  

Note: Since Java 7, JDBC has ability to use try-with-resources statement to


automatically close resources of type Connection, ResultSet, and Statement.

Java Database Connectivity with Oracle

To connect java application with the oracle database, we need to follow 5 following
steps. In this example, we are using Oracle 10g as the database. So we need to
know following information for the oracle database:

1. Driver class: The driver class for the oracle database is


oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these information from the
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the
oracle database.

Create a Table
Before establishing connection, let's first create a table in oracle database.
Following is the SQL query to create a table.

1. create table emp(id number(10),name varchar2(40),age number(3));  

xample to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data from
emp table. Here, system and oracle are the username and password of the Oracle
database.

1. import java.sql.*;  
2. class OracleCon{  
3. public static void main(String args[]){  
4. try{  
5. //step1 load the driver class  
6. Class.forName("oracle.jdbc.driver.OracleDriver");  
7. //step2 create  the connection object  
8. Connection con=DriverManager.getConnection(  
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
10.//step3 create the statement object  
11.Statement stmt=con.createStatement();  
12.//step4 execute query  
13.ResultSet rs=stmt.executeQuery("select * from emp");  
14.while(rs.next())  
15.System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
16.//step5 close the connection object  
17.con.close();  
18.}catch(Exception e){ System.out.println(e);}  }  }  

Two ways to load the jar file:

1. paste the ojdbc14.jar file in jre/lib/ext folder


2. set classpath

1) paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file
here.

2) set classpath:
There are two ways to set the classpath:

 temporary
 permanent

How to set the temporary classpath:


Firstly, search the ojdbc14.jar file then open command prompt and write:

1) Statement  –  Used to execute normal SQL queries.


2) PreparedStatement  –  Used to execute dynamic or parameterized SQL
queries.
3) CallableStatement  –  Used to execute the stored procedures.

1) Statement

Statement interface is used to execute normal SQL queries. You can’t pass the
parameters to SQL query at run time using this interface. This interface is preferred
over other two interfaces if you are executing a particular SQL query only once.
The performance of this interface is also very less compared to other two
interfaces. In most of time, Statement interface is used for DDL statements like
CREATE, ALTER, DROP etc. For example, ?

//Creating The Statement Object

  Statement stmt = con.createStatement();

  //Executing The Statement

  stmt.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL,


NAME VARCHAR)");

2) PreparedStatement

PreparedStatement is used to execute dynamic or parameterized SQL queries.


PreparedStatement extends Statement interface. You can pass the parameters to
SQL query at run time using this interface. It is recommended to use
PreparedStatement if you are executing a particular SQL query multiple times.
It gives better performance than Statement interface. Because, PreparedStatement
are precompiled and the query plan is created only once irrespective of how many
times you are executing that query. This will save lots of time. ?

//Creating PreparedStatement object

  PreparedStatement pstmt = con.prepareStatement("update STUDENT set NAME


= ? where ID = ?");

  //Setting values to place holders using setter methods of PreparedStatement object

  pstmt.setString(1, "MyName");   //Assigns "MyName" to first place holder

   pstmt.setInt(2, 111);     //Assigns "111" to second place holder

 //Executing PreparedStatement

 pstmt.executeUpdate();

2) PreparedStatement

PreparedStatement is used to execute dynamic or parameterized SQL queries.


PreparedStatement extends Statement interface. You can pass the parameters to
SQL query at run time using this interface. It is recommended to use
PreparedStatement if you are executing a particular SQL query multiple times.
It gives better performance than Statement interface. Because, PreparedStatement
are precompiled and the query plan is created only once irrespective of how many
times you are executing that query. This will save lots of time. ?

//Creating PreparedStatement object

  PreparedStatement pstmt = con.prepareStatement("update STUDENT set NAME


= ? where ID = ?");

  //Setting values to place holders using setter methods of PreparedStatement object

  pstmt.setString(1, "MyName");   //Assigns "MyName" to first place holder

  pstmt.setInt(2, 111);     //Assigns "111" to second place holder

 //Executing PreparedStatement

 pstmt.executeUpdate();

3) CallableStatement

CallableStatement is used to execute the stored procedures. CallableStatement


extends PreparedStatement. Usng CallableStatement, you can pass 3 types of
parameters to stored procedures. They are : IN – used to pass the values to stored
procedure, OUT – used to hold the result returned by the stored procedure and IN
OUT – acts as both IN and OUT parameter. Before calling the stored procedure,
you must register OUT parameters using registerOutParameter() method of
CallableStatement. The performance of this interface is higher than the other two
interfaces. Because, it calls the stored procedures which are already compiled and
stored in the database server. ?

//Creating CallableStatement object

 CallableStatement cstmt = con.prepareCall("{call anyProcedure(?, ?, ?)}");

 //Use cstmt.setter() methods to pass IN parameters

 //Use cstmt.registerOutParameter() method to register OUT parameters


 //Executing the CallableStatement

 cstmt.execute();

 //Use cstmt.getter() methods to retrieve the result returned by the stored procedure

tatement Vs PreparedStatement Vs CallableStatement In Java :


Statement PreparedStatement CallableStatement

It is used to execute
It is used to execute normal
parameterized or dynamic It is used to call the stored procedures.
SQL queries.
SQL queries.

It is preferred when a It is preferred when a


It is preferred when the stored procedu
particular SQL query is to particular query is to be
executed.
be executed only once. executed multiple times.

You cannot pass the You can pass the parameters


You can pass 3 types of parameters us
parameters to SQL query to SQL query at run time
interface. They are – IN, OUT and IN
using this interface. using this interface.

This interface is mainly It is used for any


used for DDL statements kind of SQL queries which It is used to execute stored procedures
like CREATE, ALTER, are to be executed multiple functions.
DROP etc. times.

The performance of this


interface is better than the
The performance of this
Statement interface (when The performance of this interface is hi
interface is very low.
used for multiple execution
of same query).
Java JDBC Tutorial : SQL CREATE, INSERT, SELECT, UPDATE And
DELETE Examples

Step 1 : Registering The Driver Class

First step in establishing the connection with any database is registering the JDBC
driver class of that database with DriverManager. As we are using Oracle database
in our examples, we register ‘oracle.jdbc.driver.OracleDriver‘ class, which is the
JDBC driver class of the Oracle, with the DriverManager. As this step has to be
performed only once for the whole execution, it is better to keep this step in Static
Initialization Block. Don’t forget to update your classpath with JDBC driver of the
Oracle database. Otherwise you will get ClassNotFoundException at run time.

Step 2 : Creating The Connection Object

In the second step, we create java.sql.Connection object using


DriverManager.getConnection() method by passing
URL(jdbc:oracle:thin:@localhost:1521:XE), username and password of the
database.

Step 3 : Creating The Statement Object


In the third step, we create java.sql.Statement object using con.createStatement()
method where ‘con’ is the reference to Connection object created in the second
step.

Step 4 : Executing The Queries

n the fourth step, we send the queries to the database. While sending we use
following methods of Satement object depending upon the type of queries we are
sending to the database.

ResultSet executeQuery(String sql) throws SQLException : This method is


generally used for SQL query statements which retrieve some data from the
database. For example SELECT statement. This method returns
java.sql.ResultSet object which contains the results returned by the SELECT
query.

int executeUpdate(String sql) throws SQLException : This method is generally


used for SQL statements which update the database. For example INSERT,
UPDATE and DELETE. This method is also used for SQL statements which
return nothing. For example CREATE and ALTER statements. This method
returns an int value that represents the number of rows affected by the query. This
value will be 0 for the statements which return nothing.

boolean execute(String sql) throws SQLException : This method can be used to


execute any kind of SQL statements. If you don’t know which method to use for
your SQL query, then this method is the best option. This method returns a boolean
value. TRUE indicates that query returned ResultSet object and FALSE indicates
that query returned an int value.

Step 5 : Closing The DB Resources

In the last step, we close all the DB resources – Connection, Statement and
ResultSet objects.

1) JDBC – SQL CREATE Table Example ?


import java.sql.*;

public class CreateTableExample

{
    static

    {

        //STEP 1 : Registering The Driver Class

         try

        {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        }

        catch (ClassNotFoundException e)

        {

            System.out.println("Unable To Load The Driver class");

        }

    }

     public static void main(String[] args)

    {

        Connection con = null;

         Statement stmt = null;

         try

        {

            //Database Credentials

              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();

             //Constructing The SQL Query

             String sql = "CREATE TABLE EMPLOYEE(" +

                    "ID NUMBER NOT NULL, " +

                    "FIRST_NAME VARCHAR2(200), " +

                    "LAST_NAME VARCHAR2(200), " +

                    "DISIGNATION VARCHAR2(200))";

             //Step 4 : Executing The Query

             //We are using executeUpdate() method as we are executing CREATE


statement

             int i = stmt.executeUpdate(sql);

             if(i == 0)

            {

                System.out.println("Table is created");

            }

            else

            {

                System.out.println("Table is not created");

            }

        }
        catch (SQLException e)

        {

            e.printStackTrace();

        }

        finally

        {

            //STEP 5 : Closing The DB Resources

             //Closing the Statement object

            try

            {

                if(stmt!=null)

                {

                    stmt.close();

                    stmt=null;

                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }

             //Closing the Connection object

             try
            {

                if(con!=null)

                {

                    con.close();

                    con=null;

                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }

        }

    }

2) JDBC – SQL INSERT Statement Example ?


import java.sql.*;

 public class InsertStatementExample

    static

    {

        //STEP 1 : Registering The Driver Class

         try
        {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        }

        catch (ClassNotFoundException e)

        {

            System.out.println("Unable To Load The Driver class");

        }

    }

     public static void main(String[] args)

    {

        Connection con = null;

        Statement stmt = null;

         try

        {

            //Database Credentials

            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();

             //Constructing The SQL Query

             String sql = "INSERT INTO EMPLOYEE VALUES" +

                    "(111, 'Navin', 'Sharma', 'CEO')";

             //Step 4 : Executing The Query

             //We are using executeUpdate() method as we are executing INSERT


statement

             int i = stmt.executeUpdate(sql);

             if(i != 0)

            {

                System.out.println("Row is created");

            }

            else

            {

                System.out.println("Row is not created");

            }

        }

        catch (SQLException e)

        {

            e.printStackTrace();

        }

        finally

        {
            //STEP 5 : Closing The DB Resources

            //Closing the Statement object

            try

            {

                if(stmt!=null)

                {

                    stmt.close();

                    stmt=null;

                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }

             //Closing the Connection object

             try

            {

                if(con!=null)

                {

                    con.close();

                    con=null;
                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }

        }

    }

3) JDBC – SQL SELECT Statement Example ?


import java.sql.*;

public class SelectStatementExample

    static

    {

        //STEP 1 : Registering The Driver Class

         try

        {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        }

        catch (ClassNotFoundException e)

        {
            System.out.println("Unable To Load The Driver class");

        }

    }

     public static void main(String[] args)

    {

        Connection con = null;

         Statement stmt = null;

         ResultSet rs = null;

         try

        {

            //Database Credentials

            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();

             //Constructing The SQL Query

             String sql = "SELECT * FROM EMPLOYEE";

             //Step 4 : Executing The Query

             //We are using executeQuery() method as we are executing SELECT


statement
             rs = stmt.executeQuery(sql);

             //Processing the ResultSet object

             while (rs.next())

            {

                System.out.println("ID :"+rs.getInt(1));

                 System.out.println("First Name : "+rs.getString(2));

                 System.out.println("Last Name :"+rs.getString(3));

                 System.out.println("Designation :"+rs.getString(4));

                 System.out.println("-------------------");

            }

        }

        catch (SQLException e)

        {

            e.printStackTrace();

        }

        finally

        {

            //STEP 5 : Closing The DB Resources

             //Closing the ResultSet object

                      try

            {

                if(rs!=null)
                {

                    rs.close();

                    rs=null;

                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }

             //Closing the Statement object

                  try

            {

                if(stmt!=null)

                {

                    stmt.close();

                    stmt=null;

                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }
 

            //Closing the Connection object

             try

            {

                if(con!=null)

                {

                    con.close();

                    con=null;

                }

            }

            catch (SQLException e)

            {

                e.printStackTrace();

            }

        }

    }

4) JDBC – SQL UPDATE Statement Example ?


import java.sql.*;

public class UpdateStatementExample

    static
    {

        //STEP 1 : Registering The Driver Class

         try

        {

            Class.forName("oracle.jdbc.driver.OracleDriver");        }

        catch (ClassNotFoundException e)        {

            System.out.println("Unable To Load The Driver class");        }    }

     public static void main(String[] args)    {

        Connection con = null;

         Statement stmt = null;

         try        {

            //Database Credentials

           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();

             //Constructing The SQL Query

                 String sql = "UPDATE EMPLOYEE SET FIRST_NAME='Rakesh', " +


                    "LAST_NAME='Malhotra' WHERE DISIGNATION='CEO'";

             //Step 4 : Executing The Query

            //We are using executeUpdate() method as we are executing UPDATE


statement

             int i = stmt.executeUpdate(sql);

             if(i != 0)            {

                System.out.println("Record is updated");            }

            else            {

                System.out.println("Record is not updated");            }        }

        catch (SQLException e)        {

            e.printStackTrace();        }

        finally        {

            //STEP 5 : Closing The DB Resources

             //Closing the Statement object

                try            {

                if(stmt!=null)                {

                    stmt.close();

                    stmt=null;                }            }

            catch (SQLException e)            {

                e.printStackTrace();            }

             //Closing the Connection object

             try            {

                if(con!=null)                {
                    con.close();

                    con=null;                }            }

            catch (SQLException e)            {

                e.printStackTrace();            }        }    }}

5) JDBC – SQL DELETE Statement Example ?


import java.sql.*;

 public class DeleteStatementExample{

    static    {

        //STEP 1 : Registering The Driver Class

         try        {

            Class.forName("oracle.jdbc.driver.OracleDriver");        }

        catch (ClassNotFoundException e)        {

            System.out.println("Unable To Load The Driver class");        }    }

     public static void main(String[] args)    {

        Connection con = null;

         Statement stmt = null;

         try        {

            //Database Credentials

             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();

            //Constructing The SQL Query

             String sql = "DELETE FROM EMPLOYEE WHERE ID=111";

             //Step 4 : Executing The Query

             //We are using executeUpdate() method as we are executing DELETE


statement

             int i = stmt.executeUpdate(sql);

             if(i != 0)            {

                System.out.println("Record is deleted");            }

            else            {

                System.out.println("Record is not deleted");            }        }

        catch (SQLException e)        {

            e.printStackTrace();        }

        finally        {

            //STEP 5 : Closing The DB Resources

            //Closing the Statement object

               try            {

                if(stmt!=null)                {

                    stmt.close();
                    stmt=null;                }            }

            catch (SQLException e)            {

                e.printStackTrace();            }

             //Closing the Connection object

             try            {

                if(con!=null)                {

                    con.close();

                    con=null;                }            }

            catch (SQLException e)            {

                e.printStackTrace();             }        }    }}

Difference Between executeQuery() Vs executeUpdate() Vs execute() In JDBC

executeQuery(), executeUpdate() and execute() are the methods of


java.sql.Statement interface of JDBC API which are used to execute the SQL
statements.  If you are a Java beginner, you may find them confusing because all
three spell very similar. And also you will be in confusion about which method to
use for which SQL statements.

n this post, we will discuss in detail about which method to use for which SQL
statements and how executeQuery(), executeUpdate() and execute() methods
differ from each other. It is also one of the tricky java interview question. So it is
better to know the differences between these methods before attending an
interview.

Let’s discuss them one by one.

ResultSet executeQuery(String sql) throws SQLException :

This method is used for SQL statements which retrieve some data from the
database. For example is SELECT statement. This method is meant to be used for
select queries which fetch some data from the database. This method returns
one java.sql.ResultSet object which contains the data returned by the query.

int executeUpdate(String sql) throws SQLException :

This method is used for SQL statements which update the database in some way.
For example INSERT, UPDATE and DELETE statements. All these statements
are DML(Data Manipulation Language) statements. This method can also be used
for DDL(Data Definition Language) statements which return nothing. For example
CREATE and ALTER statements. This method returns an int value which
represents the number of rows affected by the query. This value will be 0 for the
statements which return nothing.

boolean execute(String sql) throws SQLException :

This method can be used for all types of SQL statements. If you don’t know which
method to use for you SQL statements, then this method can be the best option.
This method returns a boolean value. TRUE indicates that statement has returned
a ResultSet object and FALSE indicates that statement has returned an int value or
returned nothing.

executeQuery() Vs executeUpdate() Vs execute() In JDBC :

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5 following
steps. In this example, we are using Oracle 10g as the database. So we need to
know following information for the oracle database:

1. Driver class: The driver class for the oracle database is


oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these information from the
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the
oracle database.

Create a Table
Before establishing connection, let's first create a table in oracle database.
Following is the SQL query to create a table.

1. create table emp(id number(10),name varchar2(40),age number(3));  

Example to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data from
emp table. Here, system and oracle are the username and password of the Oracle
database.

1. import java.sql.*;  
2. class OracleCon{  
3. public static void main(String args[]){  
4. try{  
5. //step1 load the driver class  
6. Class.forName("oracle.jdbc.driver.OracleDriver");  
7. //step2 create  the connection object  
8. Connection con=DriverManager.getConnection(  
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
10.//step3 create the statement object  
11.Statement stmt=con.createStatement();  
12.//step4 execute query  
13.ResultSet rs=stmt.executeQuery("select * from emp");  
14.while(rs.next())  
15.System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
16.//step5 close the connection object  
17.con.close();  
18.}catch(Exception e){ System.out.println(e);}  }  }  

You might also like