Monday 24 October 2016

Close the connection

Close the connection

  • To close the connection, we need to call close().
  • close() method presents in java.sql.Connection interface.
  • Once if we call the close() method then automatically statement will be closed.
Syntax
             public void close()throws SQLException
Example
             con.close();
-------------------------------------------------------------------------------------
Program         :       closing connection
Program name  :      ConCloseDemo1.java
Output             :         
 Driver is Registered successfully
 got Connection from DB success
 Statement object created successfully
 Table created successfully
 Connection closed successfully

import java.sql.*;
class ConCloseDemo1
{
public static void main(String args[])throws SQLException
{
//step-1:Register the JDBC driver

Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
System.out.println(“Registered succesfully”);

//step-2: get the connection from DB server

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","nireekshan");
System.out.println("got Connection from DB"+con);

//step-3 create the Statement object

Statement statement = con.createStatement();
System.out.println("Statement object created successfully");

       //step-4 execute the query

String createTableQuery = “create table emp1(eno number(5),ename varchar2(10),address varchar2(10))”;

statement.executeUpdate(createTableQuery);
System.out.println("Table created successfully");

//step-5 close the connection

con.close();
System.out.println("Connection closed successfully");
}
}

Note:
To compile above java program we have to set the class path to ojdbc14.jar, so, keep this jar in corresponding directory then set the class path.
Set class path:
  • C:\Nireekshan\JDBC>set classpath=ojdbc14.jar;.;
Compile      :          javac ConCloseDemo1.java
Run            :          java ConCloseDemo1
Output        :         
Driver is Registered successfully
got Connection from DB success
Statement object created successfully
Table created successfully
Connection closed successfully
-------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan