JDBC – Prepared Statement

JDBC – Prepared Statement 2017-06-03T23:39:04+00:00

The Prepared Statement Interface:

The Prepared Statement interface is used to execute a dynamic query (parameterized SQL statement) with IN parameter.

IN Parameter:-

In some situation where we need to pass different values to an query then such values can be specified as a “?” in the query and the actual values can be passed using the setXXX() method at the time of execution.

Syntax :

setXXX(integer data ,XXX value);

Where XXX means a data type as per the value we want to pass in the query.

For example,

String query = “Select * from Data where ID = ? and Name = ? “;

PreparedStatement ps = con.prepareStatement(query);

ps.setInt(1, 1);

ps.setString(2, “Ashutosh Abhangi”);

The Prepared statement interface has several methods to execute the parameterized SQL statements and retrieve appropriate result as per the query sent to the database.

Some of the most common methods are as given below

 

Method

Description

void close() This method frees an object of type  Prepared Statement from database and other JDBC resources.
boolean execute() This method executes the dynamic query in the object of type Prepared Statement.The getResult() method is used to retrieve the result.
ResultSet executeQuery() This method is used to execute the dynamic query in the object of type Prepared Statement and returns the object of type ResultSet.
Int executeUpdate() This method executes the SQL statement in the object of type Prepared Statement. The SQL statement may be a SQL insert, update and delete statement.
ResultSetMetaData getMetaData() The ResultSetMetaData means a deta about the data of ResultSet.This method retrieves an object of type ResultSetMetaData that contains information about the columns of the ResultSet object that will be return when a query is execute.
int getMaxRows() This method returns the maximum number of rows those are generated by the executeQuery() method.

The example program for Prepared Statement interface and its methods are given in next chapter for different databases.

Prev Next