Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
18.6 Prepared Statements (Precompiled Queries)
497
Listing 18.17 ExitListener.java
package coreservlets;
import java.awt.*;
import java.awt.event.*;
/** A listener that you attach to the top level Frame
* or JFrame of your application, so quitting the
* frame exits the application.
*/
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
18.6 Prepared Statements
(Precompiled Queries)
If you are going to execute similar SQL statements multiple times, using
prepared statements can be more efficient than executing a raw query each
time. The idea is to create a parameterized statement in a standard form that
is sent to the database for compilation before actually being used. You use a
question mark to indicate the places where a value will be substituted into
the statement. Each time you use the prepared statement, you simply replace
some of the marked parameters, using a
setXxx
call corresponding to the
entry you want to set (using 1 based indexing) and the type of the parameter
(e.g.,
setInt
,
setString
, and so forth). You then use
executeQuery
(if you
want a
ResultSet
back) or
execute
/
executeUpdate
(for side effects) as
with normal statements. For instance, if you were going to give raises to all
the personnel in the
employees
database, you might do something like the
following:
Connection connection =
DriverManager.getConnection(url, user, password);
String template =
"UPDATE employees SET salary = ? WHERE id = ?";
PreparedStatement statement =
connection.prepareStatement(template);
float[] newSalaries = getNewSalaries();
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved