Java Reference
In-Depth Information
PreparedStatements are nothing more than statements that are precompiled.
Precompilation means that these statements can be executed more efficiently than
simple statements, particularly in situations where a Statement is executed
repeatedly in a loop.
PreparedStatements can contain placeholders for variables known as IN parameters,
which are set using setter methods. A typical setter method looks like this:
public void setObject(int parameterIndex, Object x) throws SQLException
An example of this is the following line, which sets integer parameter #1 equal to 2:
pstmt.setInt(1, 2);
Use of PreparedStatements is fairly intuitive, as shown in Listing 4-2 .
Listing 4-2: Using a PreparedStatement
package java_databases.ch04;
import java.sql.*;
public class PreparedStmt{
public static void main(String args[]){
int qty;
float cost;
String name;
String desc;
String query = ("SELECT * FROM Stock WHERE Item_Number = ?";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection ("jdbc:odbc:Inventory");
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setInt(1, 2);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
name = rs.getString("Name");
desc = rs.getString("Description");
qty = rs.getInt("Qty");
cost = rs.getFloat("Cost");
System.out.println(name+", "+desc+"\t: "+qty+"\t@ $"+cost);
}
}
catch(ClassNotFoundException e){
e.printStackTrace();
Search WWH ::




Custom Search