Databases Reference
In-Depth Information
An INSERT or DELETE statement can be executed using the Statement object
in the same fashion.
PreparedStatement
An object of PreparedStatement (or a class implementing the
PreparedStatement interface) can be used to run the queries, which can contain
parameter markers. A PreparedStatement object can be created using the
prepareStatement method of Connection object. PreparedStatement extends the
Statement interface.
If the SQL statement contains parameter markers, the values for these
parameter markers need to be set before executing the statement. Value can be
set using set XXX methods of PreparedStatement object where XXX denoted the
data type of the parameter marker. set XXX methods are also called setter
methods.
The following are the examples of set XXX methods:
setInt
setString
setDouble
setBytes
setClob
setBlob
After setting the parameter values, the SQL statement can be executed using
any of the executeQuery, executeUpdate, or execute method based on the SQL
type.
SELECT using PreparedStatement object
Example 5-7 gives the code snippet for the method isCustomer from the
application code. The method passes the value of the customer id to the method,
which is used to pass the value to the SELECT query. The method returns null if
the customer id does not exist.
Example 5-7 SELECT using PreparedStatement object
String query="select info from customer where cid=?";
PreparedStatement stmt=con.prepareStatement(query);
stmt.setInt(1,id);
ResultSet rs=stmt.executeQuery();
if(!rs.next())
return null;
else
return rs.getString(1);
Search WWH ::




Custom Search