JDBC Prepared statement Close

The code illustrates you an example from JDBC Prepared Statement Close.

JDBC Prepared statement Close


The Prepared statement interface extends from statement. An statement specify a precompiled SQL Statement. This specify a same object, that execute multiple times.

Understand with Example

The code illustrates you an example from JDBC Prepared Statement Close. In this program, the code describe how the Jdbc Prepared statement is closed. For this we have a class Jdbc Prepared statement, that include the main method and the list of steps to be carried out are as follow-

Before implementing class, import a  Java.sql package, that contains a set of classes defining network interface for interaction between java front-end application and database.

 Inside the main( ) method, we have a try block includes the loading a driver by calling a class.forName( ) and accept driver class as argument.

 The  DriverManager.getConnection ( ) return you  a connection object. This object return you a  built in  connection between url and database.

  prepareStatement ( ) :This method is used  to execute the same  statement object many times, This reduces the execution time for statement.

 executeQuery( ): This method is used to retrieve the record set from a table. The select statement return you a result set .

  next ( ) : This method return you the next elements in the series.

  getString ( ):The Result Set call a getString ( ),returns you a string object representation

  close ( ) :The prepared statement object call close ( ),that close the connection between url  and database.

Finally the print ln print the Id,Name respectively from the result set as output.

In case there is an exception in try block, The catch block caught and handle the exception.


import java.sql.*;

public class JdbcPreparedstatementClose {

  public static void main(String args[]) {

  Connection con = null;
  PreparedStatement pst = null;
  ResultSet rs = null;

  String url = "jdbc:mysql://localhost:3306/";
  String db = "komal";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";

  try {

  con = DriverManager.getConnection(url + db, user, pass);

  pst = con.prepareStatement("select * from stu");
  rs = pst.executeQuery();

  while (rs.next()) {
  System.out.print(rs.getString(1) + "\t");
  System.out.print(rs.getString(2) + "\t ");

  catch (Exception e) {


Id	Name	Class
1	komal	 11
2	santosh	 11
3	rakesh	 9
4	ajay	 11
5	bhanu	 10

Download code