4.2.3.3.4 Executing the PreparedStatement Object
As we discussed in Section 3.3.2 in Chapter 3, three execution methods can be called to perform the data action against the database. Refer to Tables 4.4 and 4.5, where it can be seen that both the
Statement and PreparedStatement interfaces contain these three methods:
- executeQuery()
- executeUpdate()
- execute()
The difference between these three methods in both interfaces is that all three execution methods
defined in the Statement interface need an argument, which works as a query statement passed into the database. However, the three methods defined in the PreparedStatement interface have no argument, which means that the query statement has been built and passed to the database by using the PreparedStatement object when it is created.
Figure 4.7 shows example code for calling the executeQuery() method to perform a login process.
First, the query statement query is created in which two placeholders (?) are used since we have two dynamic parameters, username and password, to be passed into our sample database, CSE _ DEPT.

FIGURE 4.7 Code example for the execution of a PreparedStatement.
Then, with a try-catch block, a PreparedStatement object is created with the query statement as an argument. Two setString() methods defined in the PreparedStatement interface are used to initialize these two dynamic parameters (user-name = “cse”, password = “mack8000”). Finally, the executeQuery() method defined in the PreparedStatement interface is called to run this query statement, and the results are returned and stored in a ResultSet object.
In addition to using the executeQuery() method, the PreparedStatement object can also use another two methods, executeUpdate() and execute(), to perform a data action. However, those methods have different functionalities and should be applied in different situations. For more detailed information about these methods, refer to Section 4.2.3.8.
Compared with the Statement interface, the advantage of using a PreparedStatement interface is that it can perform a dynamic query with known or unknown dynamic parameters as inputs. Most of the time, those dynamic parameters are input parameters and can be defined as IN variables. However, you do not need to specify those parameters with an IN keyword when using a PreparedStatement interface.