Using prepared statements
In this recipe, you will learn how to use a prepared statement—a statement template that can be stored in the database and executed efficiently with different input values.
Getting ready
An object of PreparedStatement
—a subinterface of Statement
—can be precompiled and stored in the database and then used to efficiently execute the SQL statement multiple times for different input values. Similar to an object of Statement
(created by the createStatement()
method), it can be created by the prepareStatement()
method of the same Connection
object.
The same SQL statement that was used to generate Statement
can be used to generate PreparedStatement
too. In fact, it is a good idea to consider using PrepdaredStatement
for any SQL statement that is called multiple times, because it performs better than Statement
. To do this, all we need to change are these two lines in the sample code of the previous section:
try (Statement st = conn.createStatement()) { boolean res = st.execute...