PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.

Let's see the example of parameterized query:

String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method

public void setInt(int paramIndex, int value)

public void setString(int paramIndex, String value)

public void setFloat(int paramIndex, float value)

public void setDouble(int paramIndex, double value)

public int executeUpdate()

public ResultSet executeQuery()

sets the integer value to the given parameter index.

sets the integer value to the given parameter index.

sets the String value to the given parameter index.

sets the float value to the given parameter index.

sets the double value to the given parameter index.

executes the query. It is used for create, drop, insert, update, delete etc.

executes the select query. It returns an instance of ResultSet.

Example of PreparedStatement interface that inserts the record

Flash Soon


Output

Example of PreparedStatement interface that updates the record

Flash Soon


Output

Example of PreparedStatement interface that deletes the record

Flash Soon


Output

Example of PreparedStatement interface that retrieve the records of a table

Flash Soon


Output

Example of PreparedStatement to insert records until user press n

Flash Soon


Output


Advertisement

© Sapster 2017