Using Prepared Statements
Sometimes it is more convenient or more efficient to use a PreparedStatement object for
sending SQL statements to the database. This special type of statement is derived from
the more general class, Statement, that you already know.
When to Use a PreparedStatement Object:
Sometimes it is more convenient or more efficient to use a PreparedStatement object for
sending SQL statements to the database. This special type of statement is derived from
the more general class, Statement, that you already know.
When to Use a PreparedStatement Object:
- If you want to execute a Statement object many times, it will normally reduce execution
time to use a PreparedStatement object instead. - The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created.
- The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled.
- As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled.
- This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
- Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters.
- The advantage of using SQL statements that take parameters is that you can use the same
statement and supply it with different values each time you execute it.
- Creating a PreparedStatement Object :
- As with Statement objects, you create PreparedStatement objects with a Connection method. Using our open connection con from previous examples, you might write code
such as the following to create a PreparedStatement object that takes two input
parameters:
- PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
- The variable updateSales now contains the SQL statement,
- "UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ?" ,
- which has also, in most cases, been sent to
the DBMS and been precompiled
-
Buy It Now
0 comments:
Post a Comment