Prepared Statement Return Generated Keys

An interface for a precompiled SQL Statement. An SQL Statement is put into a PreparedStatement and is precompiled so that it can be executed efficiently multiple times. Setter methods are supplied in the PreparedStatement interface for the setting of IN parameters for the statement.

Java Preparedstatement Return Generated Keys

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

Keys

Let's see the example of parameterized query:

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:

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

MethodDescription
public void setInt(int paramIndex, int value)sets the integer value to the given parameter index.
public void setString(int paramIndex, String value)sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value)sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value)sets the double value to the given parameter index.
public int executeUpdate()executes the query. It is used for create, drop, insert, update, delete etc.
public ResultSet executeQuery()executes the select query. It returns an instance of ResultSet.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

Prepared Statement Return Generated Keys 2016

Now insert records in this table by the code given below:

Java Prepared Statement Return Generated Keys

Example of PreparedStatement interface that updates the record

Example of PreparedStatement interface that deletes the record

Prepared Statement Return Generated Keys

Example of PreparedStatement interface that retrieve the records of a table

Example of PreparedStatement to insert records until user press n

Prepared Statement Return Generated Keys Pdf

Statement.return_generated_keys