JDBC – PreparedStatement

PreparedStatement interface:

  • It is the extension of Statement interface.
  • It is used to execute parameterized query.
  • PreparedStatement improve the performance because query is compiled only once.
  • For example,
    • String sql=”insert into account values(?,?,?)”;
StatementPreparedStatement
It is used to execute static sql queriesIt is used to execute sql statement many times.
Doesn’t accept input  parametersAccess input parameters at runtime.
Statement st; st=conn.createStatement();PreparedStatement ps; String s=”Update Employees SET age=? WHERE id=?”; ps=conn.prepareStatement(s);

Setter methods: PreparedStatement providing setter methods by which we can set values to query parameters.

public void setInt(int paramIndex, int value)Sets int value to parameter
public void setString(int paramIndex, String value)Sets string value to parameter
public void setFloat(int paramIndex, float value)Sets float value to parameter
public void setDouble(int paramIndex, double value)Sets double value to parameter

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

Other methods of PreparedStatement:

  1. public int executeUpdate() : executes the query. It is used for create, drop, insert, update, delete etc.
  2. public ResultSet executeQuery() : executes the select query. It returns an instance of ResultSet.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top